3

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?

3 Answers 3

12

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}"));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, works great. You left out a closing bracket btw
5

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.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.