How can I filter a list of objects using a lambda expression?

I know that I should not have id with the same value. It is simply fictitious, so ignore it.

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 the Lambda expression to retrieve all cars with id 1.

Expected Result:

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

The problem is more filtering the list of objects based on the foreign key.

+5
source share
2 answers

Use LINQ:

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

Usage List<T>.FindAll:

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

I would prefer a personal LINQ approach - note that this is lazy, while FindAllimmediately browsing the entire list and building a new list with the results.

+15

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

All Articles