开发者

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

开发者 https://www.devze.com 2022-12-24 17:50 出处:网络
I know I shouldn\'t have id\'s with the same value. This 开发者_StackOverflow社区is just fictitious, so overlook that.

I know I shouldn't have id's with the same value. This 开发者_StackOverflow社区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.


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.


Try this

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

精彩评论

暂无评论...
验证码 换一张
取 消