WHERE is used to get things from a list that is a certain way.

In other words, WHERE filters elements from a collection to satisfy a specified condition.

For example, you might want to find every dog who’s owner is Michael. To accomplish this, we use so-called Lambda Expressions which comprises the LINQ language.

public class Dog
{
    public string Name { get; set; }

    public int Age { get; set; }

    public string OwnerName { get; set; }
}

static void Main(string[] args)
{
    List<Dog> dogList = new List<Dog>();

    dogList.Add(new Dog() { Name = "Max", Age = 4, OwnerName = "Michael" });
    dogList.Add(new Dog() { Name = "Rocky", Age = 10, OwnerName = "Michael" });
    dogList.Add(new Dog() { Name = "Mortimer", Age = 14, OwnerName = "Michael" });
    dogList.Add(new Dog() { Name = "Toby", Age = 5, OwnerName = "May" });
    dogList.Add(new Dog() { Name = "Cooper", Age = 11, OwnerName = "May" });

    var michaelsDogs = dogList
        .Where(d => d.OwnerName == "Michael");

    Console.WriteLine("Michael's dogs:");
    foreach(var dog in michaelsDogs)
    {
        Console.WriteLine(dog.Name);
    }

    // Prints:
    // Max
    // Rocky
    // Mortimer

}

Here we used a string, OwnerName, to filter on the name of the owner.

We can use the int Age to find all dogs that are older than 8 years.

var oldDogs = dogList
    .Where(d => d.Age > 8);

Console.WriteLine("Old dogs:");
foreach (var dog in oldDogs)
{
    Console.WriteLine(dog.Name);
}

// Prints:
// Rocky
// Mortimer
// Cooper

You can also combine conditions.

We can combine OwnerName and Age to find Michael’s old dogs.

var michaelsOldDogs = dogList
    .Where(d => d.Age > 8 && d.OwnerName == "Michael");

Console.WriteLine("Michael's old dogs:");
foreach (var dog in michaelsOldDogs)
{
    Console.WriteLine(dog.Name);
}

// Prints:
// Rocky
// Mortimer
Twitter
YouTube
Facebook
LinkedIn
Instagram
RSS

Popular articles


Business Bro 7 YouTube

Check out my YouTube Channel - tips for increasing your salary, work satisfaction and knowledge. I will help you achieve your goals. You can do anything if you put your mind to it!

🎥 Link: BusinessBro7 - Youtube Channel

Startups vs Big Tech Company - The best Work Place for Junior and Senior programmers?