Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

lambda

linq

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.

like image 859
Orson Avatar asked Mar 24 '10 15:03

Orson


People also ask

How do you iterate through a list in Lambda?

In Java 8, forEach statement can be used along with lambda expression that reduces the looping through a Map to a single statement and also iterates over the elements of a list. The forEach() method defined in an Iterable interface and accepts lambda expression as a parameter.

How do you filter a list of objects using a stream?

Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.


2 Answers

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.

like image 108
Jon Skeet Avatar answered Oct 04 '22 12:10

Jon Skeet


Try this

var match = carList.Where(x => x.id ==1 );
like image 42
JaredPar Avatar answered Oct 04 '22 13:10

JaredPar