Monday, February 4, 2008

Comma Delimited String From An Array using LINQ

In response to the previous posting. A few weeks ago, I would certainly have solved this the same way that you did in "OldSchool" with the exception of using IEnumerable<string>. Why limit your code to just string arrays? Now that we have LINQ, we can get pretty fancy! Technically one line within the method but I split it up to aid readability.

 

static void Main(string[] args)

{

    string[] names = new string[] { "Andy", "Marcy", "Cindy", "Jennifer", "Aaron" };

 

    Console.WriteLine(NewSchool(names));

}

 

static string NewSchool(IEnumerable<string> list)

{

    return list.Aggregate(new StringBuilder(),

        (sb, n) => sb.Length == 0 ? sb.Append(n) :

         sb.Append(",").Append(n),

        sb => sb.ToString());

}

 

And for even more fun, I built a simple test harness for each of these three methods. The test: 10000 itterations where I concatenate a string array that contains 8192 elements. Junior ran 36 minutes and 41.5 seconds*. OldSchool ran 8.453 seconds. NewSchool ran 9.484 seconds. NewSchool is likely slightly slower than OldSchool because of the use of the delegate. * I was only able to run 100 itterations on Junior which ran 22.015 seconds. I then extrapolated from there. The actual result would likely be even longer given its use of memory.

No comments:

Post a Comment