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
  • 10,975
  • 8
  • 63
  • 100
theUser
  • 1,246
  • 3
  • 20
  • 39
  • 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,176
  • 4
  • 55
  • 78
2

You can use Linq:

CarObjects.Select ( c => c.Make ).Distinct().ToList()
Stephan Bauer
  • 8,611
  • 5
  • 37
  • 57
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,270
  • 3
  • 26
  • 38