A simple mistake with LINQ

I will show you in this post a simple mistake with LINQ.
Take a look to this inoffensive method:

public static IEnumerable<string> WithTwoChars(IEnumerable<string> list)
{
    return list.Where(s => s.Length.Equals(2));
}

It takes a collection of string and returns strings with two chars.

This code use the above method:

IEnumerable<string> result = WithTwoChars(SimpleWordList());
Console.WriteLine("Count is {0} ", result.Count());
Console.WriteLine("First item is {0} ", result.ToList()[0]);

But…. what is the difference between this one:

IEnumerable<string> result = WithTwohars(SimpleWordList()).ToList();
Console.WriteLine("Count is {0} ", result.Count());
Console.WriteLine("First item is {0} ", result[0]);

The difference is quite obviously the former method iterate over the coll twice. If you put a stopwatch you will notice the difference.


blog comments powered by Disqus
  • Categories

  • Archives