0

So I have a list of Car objects.

List<Car> cars = GetCars();

I want to create a list of strings that come from the Car.Name string property.

I could do this:

List<string> carNames = new List<string>();
foreach(Car car in cars)
{
    carNames.Add(car.Name);
}

Is there a more fancy way to do this? Can you do this using LINQ?

Ay Rue
  • 228
  • 1
  • 3
  • 15
  • Yes try `cars.Select(x=>x.Name).ToList();` You should have atleast googled it first before coming here. – Mahesh Mar 25 '15 at 17:32
  • this may help you, http://stackoverflow.com/questions/1786770/linq-get-distinct-values-and-fill-list I personally think what you have there is fine, nice and readable. – Sorceri Mar 25 '15 at 17:33

4 Answers4

9
var carNames = cars.Select(c => c.Name).ToList();
Szer
  • 3,426
  • 3
  • 16
  • 36
2

If you like a query expression syntax following works too:

var carNames = 
  (from c in cars
   select c.Name).ToList();
Philip Stuyck
  • 7,344
  • 3
  • 28
  • 39
1
List<Car> cars = GetCars();
List<string> carNames = cars.Select(x => x.Name).ToList();
TcKs
  • 25,849
  • 11
  • 66
  • 104
-3

var carNames = cars.Select(c => c.Name).ToList();

Philip Stuyck
  • 7,344
  • 3
  • 28
  • 39