2

I have a CarData object with the following properties:
PrimaryKey Make Model Year Drivetrain Country

I have about 1000 of these CarData objects in a List :
List<CarData> CarObjects

Is there a simple way to get a list of the distinct Makes?

default
  • 11,485
  • 9
  • 66
  • 102
theUser
  • 1,346
  • 3
  • 21
  • 40
  • Possible Duplicate: [Linq Distinct() by name for populate a dropdown list with name and value](http://stackoverflow.com/q/912188/299327) – Ryan Gates Feb 14 '13 at 15:31

3 Answers3

4
var makes = CarObjects.Select(car => car.Make).Distinct();

This transforms the list from a list of CarData to a list of Makes, and then just finds the distinct values of the new list.

Bobson
  • 13,498
  • 5
  • 55
  • 80
2

You can use Linq:

CarObjects.Select ( c => c.Make ).Distinct().ToList()
Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
1
var makeList = CarObjects.Select(a => a.Make).Distinct();

Or

List<MakeEnum> = CarObjects.Select(a => a.Make).Distinct().ToList();

As an extra bit of advice, you may want to consider having Make be an enum, since there are (presumably) a finite (and rather small) number of possible makes of cars, instead of piling them into Strings. (You don't make a mention of what kind of property Make is, so maybe you are already doing this).

NominSim
  • 8,447
  • 3
  • 28
  • 38