Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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;
like image 486
leora Avatar asked Apr 11 '11 00:04

leora


People also ask

How do you concatenate in LINQ?

In LINQ, the concatenation operation contains only one operator that is known as Concat. It is used to append two same types of sequences or collections and return a new sequence or collection. It does not support query syntax in C# and VB.NET languages. It support method syntax in both C# and VB.NET languages.

How do you concatenate items in a string?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.

How do you concatenate strings and variables?

Use the addition (+) operator to concatenate a string with a variable, e.g. 'hello' + myVar . The addition (+) operator is used to concatenate strings or sum numbers.


1 Answers

You can write

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

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

like image 85
SLaks Avatar answered Nov 15 '22 16:11

SLaks