Your Ad Here

Posted By

theroamingcoder on 09/22/09


Tagged

list empty c strings comma


Versions (?)

Remove empty values and extra whitespace from a list


 / Published in: C#
 

This is useful for handling user provided, comma separated data. For example, in the case where the user inputs " 1, 2,3,4,, 5, 6, " you would want to remove the whitespace around each item as well as the empty items to produce "1,2,3,4,5,6".

  1. List<String> items = new List<String>(" 1, 2,3,4,, 5, 6, ".Split(','));
  2. items.RemoveAll(delegate(string s){return s.Trim() == "";});
  3. items.ForEach(delegate(string s) { items[items.IndexOf(s)] = s.Trim(); });
  4. Console.WriteLine(String.Join(",",items.ToArray()));
  5. Console.ReadKey();

Report this snippet  

You need to login to post a comment.