tags:

views:

197

answers:

2

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  A: 

Try this

var match = carList.Where(x => x.id ==1 );
JaredPar
+5  A: 

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.

Jon Skeet
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 Mahy
@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>`.
Jon Skeet