Microsoft Corporation’s newest technology helps programmers take data access to the next level. It extends the .NET framework to 3.5 and integrates query, set, and transform functions/methods right within the language. It is compatible with both vb.net and c#.net. . The standard query operators allow queries to be applied to any IEnumerable<T>-based objects.
There's so much that I can cover about LINQ, but I will leave that to MSDN for you. (links at the bottom of the post). I will however give you some standard code snippets, and explain a few expressions. Click the more link to see my examples
Select
Exception: ArgumentNullException can occur if the object which is being queried is null (Nothing is VB).
1: Dim i_array() as integer = {1, 2, 3, 4, 5, 6, 7, 8, 9}
3: Dim query = from item in i_array _
6: 'LINQ words on deffered execution. This means the query
7: 'does not get executed until the for-each loop is executed.
Distinct
Exception: ArgumentNullException can occur if the object which is being queried is null (Nothing is VB).
1: ' Create a list of integers.
2: Dim ages As New List(Of Integer)(New Integer() _
3: {21, 46, 46, 55, 17, 21, 55, 55})
4:
5: ' Select the unique numbers in the List.
6: Dim distinctAges As IEnumerable(Of Integer) = ages.Distinct()
7:
8:
9: For Each age As Integer In distinctAges
10: Console.WriteLine(age)
11: Next
12:
Single()
Exception: ArgumentNullException can occur if the object which is being queried is null (Nothing is VB).
InvalidOperationException can occur if sequence contains more then one element.
Remarks: This function is very useful if you have to retrieve only one record. It will throw an exception if the matching criteria has more then one record. The best way to implement this in LINQ to SQL queries is to query a table that has a primary key. The primary key can be an autoincrement integer, or an unique indentifier. Since you have only have one unique value for each row, combining this with the Single() function, you can retreive a single object instead of an IEnumerable/IQueryable.
1: Dim i_array() as String = _
2: {"Bob", "Baker", "Adam", "Charlie", "John", "Julie", "Emily", "Maria"}
3:
4: Dim query = (from item in i_array _
5: where item.length = 7 _
6: select item).Single
7:
8: Console.Writeline (query) //output: Charlie