1

How to select distinct values from a list of objects? I want to get only a list of specific field but not a list of the whole object.

For example the collection to be queried:

name   year
Item1  2009
Item2  2009
Item3  2010
Item4  2010
Item5  2011
Item6  2011

and from that I want to return distinct years to get the below result collection

2009
2010
2011
2012

I tried

distinctyears = myCollection.GroupBy(x => x.year).Select(x => x.First()).ToList();

but that will return a collection of the whole object instead of only the year values.

Nuts
  • 2,755
  • 6
  • 33
  • 78

1 Answers1

5
distinctyears = myCollection.Select(x => x.year).Distinct()

Will return you an IEnumerable<int> (or whatever type year is)

no need to do a grouping - all you want is the year in the result, so just grab that.

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112