WHERE IN LINQ
Yesterday , we talk about how LINQ , using C# language , can select numbers the way SQL SELECT statement does. Today , we will go over examples of WHERE statement using LINQ. You can find the article showing LINQ with SELECT here. Hopefully after 2 or 3 more examples of LINQ statements , we can being to see the beauty of having the ability to interact with SQL Databases within the language directly. Lets take a look at the example then ,
LINQ Example
public void LinqWhere()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNums =
from n in numbers
where n < 5
select n;
Console.WriteLine("Numbers < 5:");
foreach (var x in lowNums)
{
Console.WriteLine(x);
}
}
As you might have guesses by simply reading the code , it take an array of integers , named numbers , from from that array , it selects those numbers less than 5 and pass it to another array. Then uses a “foreach” loop to prints out the list on each new line by itself.
You might ask what is this VAR type. It doesn’t seem to be an integer or String or anything we have seen before. Here is the definition of it from Microsoft website ,
“Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.”
It then gives two examples of using VAR and integer ,
var i = 10; // implicitly typed int i = 10; //explicitly typed
Basically , instead of saying this is an integer , you let the compiler does the job for you. Both statements above are equal as far as your program is concerned.
LINQ WHERE Conclusion
Hope it helps someone who is struggling with LINQ and also hope you enjoy the read. Its been a great Sunday for me and cya tomorrow! There will be more LINQ!