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;
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.
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.
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.
You can write
return String.Join(", ", collection.Select(o => o.Issue));
In .Net 3.5, you'll need to add .ToArray()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With