A quick one to share:
I needed to a method to quickly convert a List<string> to a plain comma delimited string. So I created this little Extension class:
public static class ListEx
{public static string ToCSVString(this List<string> l)
{StringBuilder sb = new StringBuilder();
if (l != null)
{l.ForEach(li => sb.Append(li + “, “));
}
return sb.ToString().Trim(‘ ‘, ‘,’);}
}
Of course this is still very specific to string collections only. I could have created something that does the same to say a List<T> list that is more generic but that I’ll leave for another day.
[Update]
While I’m at it – here is the opposite method:
public static List<string> ToListFromCSVString(this string s, bool ordered = false)
{List<string> list = new List<string>();
if (s != null && s.Trim().Length > 0)
{if (ordered)
list.AddRange((from sitem in s.Split(new char[] { ‘,’ }, StringSplitOptions.RemoveEmptyEntries)
orderby sitem
select sitem.Trim()).ToArray());else
list.AddRange((from sitem in s.Split(new char[] { ‘,’ }, StringSplitOptions.RemoveEmptyEntries)
select sitem.Trim()).ToArray());}
return list;
}
0 Comments.