C# Keywords Tutorial Part 99: where

C# Keywords Tutorial Part 99: where

Popular computer language C# is used to create a variety of applications, including desktop software and web apps. The “where” keyword, which is used to filter data based on specific criteria, is one of the language’s strong features. In this article, we’ll go over the “where” keyword in depth and give several C# code examples to demonstrate how to utilize it.

The “where” Keyword in C#

The “where” keyword is used in C# to specify a set of conditions that must be met by elements in a collection. This keyword is typically used in conjunction with the “IEnumerable” interface to filter data based on a specific condition.

Here’s an example of how the “where” keyword can be used in C#:

var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var evenNumbers = numbers.Where(n => n % 2 == 0);

In this example, we’ve declared a list of numbers, and we’re using the “where” keyword to filter out all the even numbers from the list. The condition we’ve specified is that the number must be divisible by 2 with no remainder.

Using the “where” Keyword with LINQ

The “where” keyword is also commonly used with Language Integrated Query (LINQ) in C#. LINQ allows developers to perform complex queries on data sources using a simple syntax, and the “where” keyword is often used to filter data.

Here’s an example of how the “where” keyword can be used with LINQ in C#:

var books = new List<Book>
    new Book { Title = "The Great Gatsby", Author = "F. Scott Fitzgerald", Year = 1925 },
    new Book { Title = "To Kill a Mockingbird", Author = "Harper Lee", Year = 1960 },
    new Book { Title = "1984", Author = "George Orwell", Year = 1949 },
    new Book { Title = "The Catcher in the Rye", Author = "J.D. Salinger", Year = 1951 }

var modernBooks = from book in books
                  where book.Year > 1950
                  select book;

In this example, we’ve created a list of books and filtered away all the books that were released before 1950 using the “where” keyword. The query has been specified using the LINQ syntax, which is clearer and shorter than conventional loops.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *