|
-
Feb 2nd, 2008, 09:31 AM
#1
[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:
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
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:
Private Structure ShopItem
Public Name As String
Public BestBefore As Date
End Structure
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:
Dim query As IEnumerable(Of String) = From item In ShopItemList _
Where (item.BestBefore >= Now.Date) _
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.
-
Feb 22nd, 2008, 12:42 PM
#2
Fanatic Member
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.
Last edited by masfenix; Feb 22nd, 2008 at 12:48 PM.
-
Mar 12th, 2008, 01:07 PM
#3
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|