Say I have a List of objects, and the object has a string property. I want to get a single comma-separated list of the value of each string property of each object in the list.
Here’s 1 way to do it (sans linq)
StringBuilder result = new StringBuilder()
foreach(myObject obj in myList)
{
result.Append(obj.TheString);
result.Append(", ");
}
// then trim the trailing ", " and call ToString() on result, etc, etc...
Here’s my first shot at linqification. Is there a better way?
string result = string.Join(", ", myList.Select(myObj => myObj.TheString).ToArray());
That’s one line of code, but it doesn’t look very efficient to me — iterate the list just to build an array, just to iterate the array and build a string… whew!
Is there a better way?
If you want efficient, use
Enumerable.AggregatewithStringBuilder:The original problem is that
String.Joinwants an array. In .NET 4, there will be an overload that takesIEnumerable<string>(and I expect it will be implemented like above).