Ever need to convert a List of strings in a comma delimited list? In the past I'd write a foreach loop. Something like:
public static string FlattenStringList(List<string> items)
{
StringBuilder str = new StringBuilder();
bool firstOne = false;
foreach (string item in items)
{
if (!firstOne)
str.Append(",");
else
firstOne = false;
str.Append(item);
}
return str.ToString();
}
Now, thanks to String.Join and Linq, I can compress it to a single expression:
string.Join(",", items.ToArray());
Also useful when the source is IEnumerable<T>, and I want a property of T flattened, consider a list of people, to get a comma delimited list of all the first names is a simple matter of:
var firstNames = string.Join(",", (from person in people select person.FirstName).ToArray());
If you need it a quote qualified, comma delimited list of first names:
var firstNames = string.Join(",", (from person in people select "\""+person.FirstName+"\"").ToArray());