Sunday, September 21, 2008

.To[Delimited]String – Using LINQ and Extension Methods to provide a delimited ToString method for Array’s, Lists, etc.

CodeProject - Seperator Delimited ToString for Array, List, Dictionary, Generic IEnumerable

“…

In C#, there is an easy way to do ToString with separator delimited for Array, List, Dictionary and Generic IEnumerables by utilizing extension method in .NET

Lets try a simple example without using String.Join directly.

int[] intArray = { 1, 2, 3 };
Console.WriteLine(intArray.ToString(","));
// output 1,2,3
List<string> list = new List<string>{"a","b","c"};
Console.WriteLine(intArray.ToString("|"));
// output a|b|c


…”




I was just thinking about doing something like this the other day. I have a number of arrays, collections, etc that I need to transform into a delimited string and while taking the fast to code, old school approach (i.e. looping) I knew there had to be a more reusable, cleaner and generally better way.



This project is one example of that better way, by using Linq with extension methods (and String.Join)…

2 comments:

Anonymous said...

Hi Greg, the link to the CodeProject is broken, I have found the original post at
http://www.codemeit.com/linq/c-array-delimited-tostring.html

Greg said...

I hate when that happens... sigh... The joy of being a reblogger. :p

Thank you catching it and for the link.