What is LINQ
Language Integrated Query (LINQ) is a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities.
Let us see an example first. Suppose there is a list of integers like this:
List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 100 };
To find all the even numbers in this list, you might write some code like this:
List<int> list1 = new List<int>(); foreach (var num in list) { if (num % 2 == 0) list1.Add(num); }
Now with LINQ, you can select all of the even numbers from this list and assign the query result to a variable in just one sentence like this:
var list2 = from number in list where number % 2 == 0 select number;
In this example list2
and list1
are equivalent. list2
contains the same numbers as list1
does. As you can see, you...