Searching for a specified instance in List

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.

2 uwagi do wpisu “Searching for a specified instance in List

  1. 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

Zostaw komentarz

Wprowadź swoje dane lub kliknij jedną z tych ikon, aby się zalogować:

Logo WordPress.com

Komentujesz korzystając z konta WordPress.com. Wyloguj /  Zmień )

Zdjęcie na Google+

Komentujesz korzystając z konta Google+. Wyloguj /  Zmień )

Zdjęcie z Twittera

Komentujesz korzystając z konta Twitter. Wyloguj /  Zmień )

Zdjęcie na Facebooku

Komentujesz korzystając z konta Facebook. Wyloguj /  Zmień )

w

Connecting to %s