Results 1 to 3 of 3

Thread: [2008] Simple LINQ examples

Threaded View

  1. #1

    Thread Starter
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    [2008] Simple LINQ examples

    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:
    VB.Net Code:
    1. Dim values() As Integer = {43, 12, 0, 75, 433, 33, 76, 21, 5, 8, 320}
    2.  
    3.         Dim query As IEnumerable(Of Integer) = From i In values _
    4.                                               Where i Mod 2 = 0 _
    5.                                               Order By i _
    6.                                               Select i
    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.

    Now, take a look at this example:
    VB.Net Code:
    1. Private Structure ShopItem
    2.         Public Name As String
    3.         Public BestBefore As Date
    4.     End Structure
    5.  
    6.     Private ShopItemList As New List(Of ShopItem)
    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:
    1. Dim query As IEnumerable(Of String) = From item In ShopItemList _
    2.                                               Where (item.BestBefore >= Now.Date) _
    3.                                               Select item.Name
    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.

    *More to come*
    Last edited by Atheist; Feb 14th, 2008 at 06:57 PM.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width