José F. Romaniello

Las aventuras y desventuras de un codificador.

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.

| More

2 comentarios:

If you change the method to ICollection<> it will work well without the ToList().
I checked the way Count() works and then stopped from using IEnumerable<> when i'm going to Count() it is my own codebase.

If it is a collection it casts to a collection and counts so you don't have that problem.

Thank you Gustavo for share this

Publicar un comentario