notAnonymousAnymore
notAnonymousAnymore

Reputation: 2687

Using String.Join for multiple items in a List

I have an entity like this:

public class Task
{
    public string TaskID { get; set; }
    public string Description { get; set; }
    public string IsComplete { get; set; }
}

I have a collection of Tasks like:

List<Task> tasks = new List<Task>();
tasks.Add(new Task() { TaskID = "1", Description = "A", IsComplete = "Yes" });
tasks.Add(new Task() { TaskID = "2", Description = "B", IsComplete = "No" });

I am trying to get the following delimited string from this collection:

1#Yes,2#No

I've managed to get as far as:

string delimitedString = String.Join(",", tasks.ToList().Select(l => l.TaskID));

...How do I further select and separate additional fields?

Upvotes: 3

Views: 981

Answers (3)

germi
germi

Reputation: 4668

You could do it the way Yuval Itzchakov proposed, but I'd rather implement a new method in Task that you can call - just to keep it easier to read.

public class Task
{
    ...
    public String ToDelimitedString()
    {
        return String.Format("{0}#{1}", TaskId, IsComplete);
    }
}

And then call it like this:

var delimString = String.Join(",", tasks.Select(t => t.ToDelimitedString()));

This way you have your format in one place and can call it from anywhere without inconsistencies.

By the way: I'd also try to find a different name for the class to avoid any possible confusion with System.Threading.Tasks.Task.

Upvotes: 5

Gilthans
Gilthans

Reputation: 1726

I think what you need is to implement a ToString for the Task, so it displays what you want.

If you can't (it isnt your code), implement a separate function:

private string StringifyTask(Task task)
{
    return string.Format("{0}#{1}", task.TaskId, task.IsComplete);
}

And then use StringifyTask as the argument of Select. Also - note you don't actually need the ToList before the Linq statement.

Upvotes: 2

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149656

Like this:

string delimitedString = 
           string.Join(",", tasks.Select(
                                  l => string.Format("{0}#{1}", l.TaskID, l.IsComplete)));

If you're using C#-6:

string delimitedString = 
            string.Join(",", tasks.Select(
                                   l => $"{l.TaskID}#{l.IsComplete}"));

Upvotes: 12

Related Questions