7

I know I shouldn't have id's with the same value. This is just fictitious, so overlook that.

I have:

List<Car> carList = new List<Car>();
carList.Add(new Car() { id = 1, name = "Honda" });
carList.Add(new Car() { id = 2, name = "Toyota" });
carList.Add(new Car() { id = 1, name = "Nissan" });

I want to use Lambda Expression to retrieve all cars that have an id of 1.

Anticipated Result:

-- Id: 1, Name: Honda
-- Id: 1, Name: Nissan

The problem is more filtering an object list based on a foreign key.

2 Answers 2

19

Use LINQ:

IEnumerable<Car> matchingCars = carList.Where(car => car.id == 1);

Using List<T>.FindAll:

List<Car> matchingCars = carList.FindAll(car => car.id == 1);

I would prefer the LINQ approach personally - note that that is lazy, whereas FindAll immediately looks through the whole list and builds a new list with the results.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't agree with the LINQ preference, you first need to know the context of the code before you can decide wether to go lazy initialized or not ....
@Tim: I would usually use LINQ with a ToList call afterwards if I wanted eager evaluation, just for a consistency. FindAll could be slightly simpler in some cases, although that does limit you to having a List<T> as a source instead of only requiring IEnumerale<T>.
5

Try this

var match = carList.Where(x => x.id ==1 );

Comments

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.