Essential LINQ
Alrighty , I shall now take a dive into LINQ from today onwards. SO what exactly is LINQ in the first place? This is one definition ,
“LINQ (Language Integrated Query) is a Microsoft programming model and methodology that essentially adds formal query capabilities into Microsoft .NET-based programming languages. LINQ offers a compact, expressive, and intelligible syntax for manipulating data. The real value of LINQ comes from its ability to apply the same query to an SQL database, a DataSet, an array of objects in memory and to many other types of data as well. LINQ requires the presence of specific language extensions.
LINQ uses an SQL-like syntax to make query expressions well beyond the capabilities of embedded SQL as implemented in programming languages. That’s because embedded SQL uses a simplified, streamlined syntax to add SQL statements to other programming languages, where there’s no attempt to integrate such statements into the native syntax and typing mechanisms. Thus, you can’t invoke native language structures such as functions in embedded SQL statements, as you can using LINQ, because it is implemented to use native syntax, structures, and typing mechanisms. Furthermore, LINQ may be used to access all kinds of data, whereas embedded SQL is limited to addressing only databases that can handle SQL queries.”
Source Here.
LINQ Example
Well then what does it look like?
It looks like this ,
public void LinqExample()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var numsPlusPlus =
from n in numbers
select n + 1;
Console.WriteLine("Numbers++:");
foreach (var i in numsPlusPlus)
{
Console.WriteLine(i);
}
}
and this prints out ,
Numbers++:
6
5
2
4
10
9
7
8
3
1
If you remember or read the post on loops I did a while back , here is the link, you will notice that it looks very similar to the for loop we did back then , except that instead of going through numbers from start to finish , I went through a group or an array of lists.
An array is simply a container of objects such as an integers we have over here. One of the main usage is to have the group sliced and diced. You could for example , 5th place of an array or maximum values of the list. Of course , a table is also an array of data. You could select the maximum value in a specific column or choose a specific value. You could imagine here that there is a table with a column header named “numbers” and the values are entered as follow ,
Numbers
5
4
1
3
9
8
6
7
2
0
Then you would do a select all statement and then add 1 to the result. The result would be similar to above and that is one of the reason you would see such statements ,
var numsPlusPlus =
from n in numbers
select n + 1;
This in SQL would be
Select * from numbers;
Hmms … I can’t seems to find a function that adds a value to the select output .. But you get the drift. This is where we will be starting out on LINQ and I hope to have more examples in future. Cya!