mercredi 9 mai 2012

C#: prefer LINQ instead of foreach

In this post, i want to focus in LINQ and its advantage on foreach.

In fact, i meet yesterday the following case: i had a list and i would remove some elements matching a criteria.

As you know C# provide a lots of interface like IQueryable, IEnumerable, etc.... And face to my problem i started by using my list as an IEnumerable through a foreach.... so wrong am i.

In fact if you try something like this:

 var collect = new Collection<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 foreach (var x in collect)
 {
    if (x % 2 == 0)
    {
       collect.Remove(x);
    }
 }
You will meet an exception: System.InvalidOperationException :  .... Because you change the collection itself during the enumeration.

But some very simple solutions exists.
1) If the collection is a List of something implementing the IList Interface you can use "RemoveAll"

collect.RemoveAll(x => x % 2 == 0);


2) If your collection doesn't implement IList, you can use the following code:

 foreach (var x in collect.Where(x => x % 2 == 0).ToList())
 {
    collect.Remove(x);
 } 


  As ToList doesn't provide a new object of type List containing only the element we want to remove and we get through this new list.

No more problems !

Aucun commentaire :

Enregistrer un commentaire