Where vs Select

Hi ,
where : This clause is used for filtering elements based on a specified condition. It’s similar to the WHERE clause in SQL. When you want to select elements that satisfy certain criteria, you use where .

select : This clause is used for projecting data into a new form. It’s similar to the SELECT clause in SQL. When you want to transform the elements in some way (like selecting specific properties, performing calculations, or projecting them into a different data structure), you use select .

(From num In numbers
Where num Mod 2 = 0
Select num * 2).ToList()

  • Where is used to filter elements based on a condition (num Mod 2 = 0 filters even numbers in this case).
  • Select is used to transform each element (double the even numbers in this case).
  • ToList() converts the resulting sequence into a list.

If the numbers collection contains the elements 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10,

  1. The Where clause filters out only the even numbers, which are 2, 4, 6, 8, and 10.
  2. The Select clause doubles each even number, resulting in 4, 8, 12, 16, and 20.
  3. Finally, ToList() converts the sequence 4, 8, 12, 16, and 20 into a list.

Together, this LINQ query filters even numbers from the numbers collection and doubles them, resulting in a list of even numbers doubled.

2 Likes