Sobes.tech
Junior — Middle

Can you explain how the Where method functions in programming language?

sobes.tech AI

Answer from AI

The Where method in C# is used to filter collections based on a specified condition. It takes a lambda expression (predicate) that returns true for elements to keep and false for those to filter out.

Example:

int[] numbers = {1, 2, 3, 4, 5, 6};
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach(var num in evenNumbers)
{
    Console.WriteLine(num); // Outputs 2, 4, 6
}

Where returns a deferred (lazy) sequence, meaning the filtering occurs during iteration over the results.