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?

2
  • Yes try cars.Select(x=>x.Name).ToList(); You should have atleast googled it first before coming here. Commented Mar 25, 2015 at 17:32
  • this may help you, stackoverflow.com/questions/1786770/… I personally think what you have there is fine, nice and readable. Commented Mar 25, 2015 at 17:33

4 Answers 4

9
var carNames = cars.Select(c => c.Name).ToList();
Sign up to request clarification or add additional context in comments.

Comments

2

If you like a query expression syntax following works too:

var carNames = 
  (from c in cars
   select c.Name).ToList();

3 Comments

But.. Its not Lambda-expression. This is query-syntax, which will be converted by compiler to fluent-syntax which contains lambda-expressions.
You mean if you DON'T like lambda?
I meant Query syntax whereas the other answers are using method syntax. Both work.
1
List<Car> cars = GetCars();
List<string> carNames = cars.Select(x => x.Name).ToList();

Comments

-3

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

1 Comment

This will return only First element of car names. Or Default.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.