I've just begun learning about LINQ and I thought it'd be good to share some simple examples to get more people aware of this great functionallity.
LINQ stands for Language-Integrated Query, and can perform queries on anything that implements the IEnumerable interface.
Here's something pretty basic:
After this code has executed, 'query' will contain every integer from the 'values' array (From i In values) that can be evenly divided into 2 (Where i Mod 2 = 0). (Order By i) specifies that the returned values should be ordered numerically. And finally, the Select operator specifies what columns to include in the result, but seeing as we're dealing with simple Integers, we dont have much choice other than returning the integer value.VB.Net Code:
Dim values() As Integer = {43, 12, 0, 75, 433, 33, 76, 21, 5, 8, 320} Dim query As IEnumerable(Of Integer) = From i In values _ Where i Mod 2 = 0 _ Order By i _ Select i
Now, take a look at this example:
A simple structure holding the name and "Best before" date of an item in a shop, and a list of the structure.VB.Net Code:
Private Structure ShopItem Public Name As String Public BestBefore As Date End Structure Private ShopItemList As New List(Of ShopItem)
This query will return the name of each grocery that has passed the "Best before" date. Take a look at the Select statement in this one, instead of returning the entire structure to the query result, I'm only returning the string from the Name field.VB.Net Code:
Dim query As IEnumerable(Of String) = From item In ShopItemList _ Where (item.BestBefore >= Now.Date) _ Select item.Name
*More to come*




Reply With Quote