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.
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.
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.
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With