Now You're Querying
LINQ is a powerful toolset in the .NET framework that enables C# developers to query and manipulate collection of objects.
LINQ stands for Language Integrated Query. LINQ makes easier and faster to write the code. LINQ can only be use with collection or list (IEnumerable<T>).
Two flavors of syntax in writing LINQ: query syntax and method syntax.
Create our list first.
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8};
List<int> numbersGreaterThanFive = new List<int>;
Now we want to store the number in numbers if it is greater than 5. (traditional way).
foreach (int number in numbers)
{
if (number > 5)
{
numbersGreaterThanFive.Add(number);
}
}
// result: 6, 7, 8
Now let's use LINQ with Query Syntax.
List<int> numbersGreaterThanFive = from number in numbers where number > 5 select number;
// error
IEnumerable<int> numbersGreaterThanFive = from number in numbers where number > 5 select number;
// result: 6, 7, 8
Now let's use LINQ with Method Syntax.
IEnumerable<int> numbersGreaterThanFive = numbers.Where(n=>n>5);