Performance of a get unique elements/group by operation on an IEnumerable<T>.

Posted by tolism7 on Stack Overflow See other posts from Stack Overflow or by tolism7
Published on 2010-04-27T14:31:35Z Indexed on 2010/04/27 14:33 UTC
Read the original article Hit count: 231

Filed under:
|
|

I was wondering how could I improve the performance of the following code:

public class MyObject
{
    public int Year { get; set; }
}

//In my case I have 30000
IEnumerable<MyObject> data = MethodThatReturnsManyMyObjects(); 

var groupedByYear = data.GroupBy(x => x.Year); 

//Here is the where it takes around 5 seconds
foreach (var group in groupedByYear) 
    //do something here.

The idea is to get a set of objects with unique year values. In my scenario there are only 6 years included in the 30000 items in the list so the foreach loop will be executed 6 times only. So we have many items needing to be grouped in a few groups.

Using the .Distinct() with an explicit IEqualityComparer would be an alternative but somehow I feel that it wont make any difference.

I can understand if 30000 items is too much and that i should be happy with the 5 seconds I get, but I was wondering if the above can be imporved performance wise.

Thanks.

© Stack Overflow or respective owner

Related posts about c#

Related posts about ienumerable