What Was I Thinking?

Follies & Foils of .NET Development
posts - 95 , comments - 352 , trackbacks - 0

QuickTip - Flatten strings to a comma delimited list

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());

Print | posted on Tuesday, December 23, 2008 1:03 AM | Filed Under [ Visual Studio ]

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

Powered by: