leora
leora

Reputation: 196539

using LINQ how can i concatenate string properties from itesm in a collection

i have a list of objects in a collection. Each object has a string property called Issue. I want to concatenate the issue from all of the items in the collection and put them into a single string. what is the cleanest way of doing this using LINQ.

here is manual way:

 string issueList = "";
 foreach (var item in collection)
 {
       if (!String.IsNullOrEmpty(item.Issue)
       {
             issueList = issueList + item.Issue + ", ";
       }
 }
 //Remove the last comma
 issueList = issueList.Remove(issueList.Length - 2);
 return issueList;

Upvotes: 7

Views: 4325

Answers (2)

TrueWill
TrueWill

Reputation: 25523

You could use ToDelimitedString from morelinq.

Upvotes: 0

SLaks
SLaks

Reputation: 887449

You can write

return String.Join(", ", collection.Select(o => o.Issue));

In .Net 3.5, you'll need to add .ToArray().

Upvotes: 21

Related Questions