Results 1 to 3 of 3

Thread: [2008] Simple LINQ examples

  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)

  2. #2
    Fanatic Member
    Join Date
    Feb 2006
    Posts
    607

    Re: [2008] Simple LINQ examples

    PART 2
    LINQ TO SQL

    Firstly I am gonna assume you have watched this video:
    http://msdn2.microsoft.com/en-ca/vbasic/bb737878.aspx

    This tutorial assumes that you have a primary key in all your tables, and a dbml file created.

    Add an entry:
    Code:
          Try
                    Dim db As New dbDataContext
                    Dim client As New client
                    client.firstname = fnametxt.Text.Trim.ToUpper
                    client.lastname = lnametxt.Text.Trim.ToUpper
                    client.email = emailtxt.Text.Trim.ToUpper
                    client.address = addresstxt.Text.Trim.ToUpper
                    client.country = countrytxt.Text.Trim.ToUpper
                               
                    db.clients.InsertOnSubmit(client)
                    db.SubmitChanges()
                                  
                Catch ex As Exception
                   'log your error here. Handle carefully.                
                End Try
    Now we edit the same client:

    Code:
    Try
                    Dim client = (From p In db.clients _
                                     Where p.id = id _
                                     Select p).Single
                    client.firstname = fnametxt.Text.Trim.ToUpper
                    client.lastname = lnametxt.Text.Trim.ToUpper
                    client.email = emailtxt.Text.Trim.ToUpper
                    client.address = addresstxt.Text.Trim.ToUpper
                    client.country = countrytxt.Text.Trim.ToUpper
                 
                    db.SubmitChanges()
            
                Catch ex As Exception
                     'log the error
                End Try
    Note: How I have brackets around my query then a .single. The .single function returns ONE RECORD. If there are more then 1 records then it will THROW an EXCEPTION. You can alternatively use .First to get the FIRST record of many if you think there are many records.

    again db.submitChanges is required to DO anything

    Code Block 3: Adding a picture using LINQ to SQL field "image". This code gets an image from the picture box. To load a picturebox, please do a search on MSDN for picturebox class.
    Code:
     
    Try
                Dim db As New dbDataContext
                Dim entry As New inventory
                             
                    Using picture As Image = PictureBox1.Image
                        Using stream As New IO.MemoryStream
                            picture.Save(stream, Imaging.ImageFormat.Jpeg)
                            entry.picture = stream.GetBuffer
                        End Using
                    End Using
    
                    db.inventories.InsertOnSubmit(entry)
                    db.SubmitChanges()
    
                    MessageBox.Show("Item has been added, closing")
                    
                End If
    
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
    There will be instances when you have autoincrement field called "id" or w/e. Obviuosly you dont assign id a value when submitting a new entry. But there will be times when you add an item, and you need to use the newly entered id to do another task.

    Code:
     Dim db As New dbDataContext
                        Dim newO As New order
                       'order has a autoincrement field "id"
                        newO.clientid = clientid
                        newO.clientname = clientlbl.Text
                                    
                        db.orders.InsertOnSubmit(newO)
                        db.SubmitChanges()
    
                        ordernumber = newO.id
    If you notice newO.id will be assigned the id of the item you just entered. This will throw an exception if you called it before submitChanges was called.

  3. #3
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: [2008] Simple LINQ examples

    If you have a structure or class that you want returned from your LINQ query, you can do that too as LINQ allows you to shape your results.

    Let's say you have

    Code:
     struct ImageLink
            {
                public string DestinationUrl;
                public string ThumbnailUrl;
            }
    (ImageLink represents a small thumbnail that links off to another page, like on Flickr)

    You can then do

    Code:
    var ResultItems = from i in SearchResults.Results
                            select new ImageLink { DestinationUrl = i.DisplayUrl, ThumbnailUrl = i.Image.ThumbnailURL };
    You then get an IEnumerable List of a structure or class that your code is already aware of so that you can deal with it appropriately. Use ResultItems.ToList() to convert it to a List<ImageLinks> if that makes you comfortable.

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