Short post about searching List. There are 3 most popular methods: foreach, delegate and lambda expression. I will introduce all of them.
Let’s say that we have List which stores cars. Car has 2 properties – brand and model.
var listOfCars = new List { new Car() { Brand = "Car1Brand", Model = "Car1Model" }, new Car() { Brand = "Car2Brand", Model = "Car2Model" }, new Car() { Brand = "Car3Brand", Model = "Car3Model" }, };
We need to find „Car2Brand” car.
You can use foreach:
foreach (var simpleCar in listOfCars) { if (simpleCar.Brand == "Car2Brand") { selectedCar = simpleCar; } }
I don’t like this method, because imagine that you have a lot of lists to search and each time you need to write at least 7! lines of code.
Second method is delegate:
selectedCar = listOfCars.Find(delegate(Car c) { return c.Brand == "Car2Brand"; });
Ok – it is shorter than foreach, but is it really readable?
Third method which I like most is using Lambda expression. Let’s look at example:
selectedCar = listOfCars.Find(c => c.Brand == "Car2Brand");
It is very simple, you don’t need to specify delegate(Car c), you only use c => c.
Hello MJ,
It might be a good idea to insert break; statement inside foreach loop:
foreach (var simpleCar in listOfCars)
{
if (simpleCar.Brand == „Car2Brand”)
{
selectedCar = simpleCar;
break; // there is no need to continue on iterating
}
}
Cheers,
Rafal
If we have a list.Add() inside, and we have a lot of duplicates, then we won’t use break.
In this case – yes, you are right 🙂