Another Way to LINQ
I was reading another installment of ScottGu's articles on his blog about using LINQ to SQL in ASP.NET with the LinqDatasource. Scott does an amazing job of explaining things very clearly so if you haven't checked his posts out already then you definitely should. It's also very nice to see him show both VB and C# code. One example that I want to point out is where he uses a Lambda Expression to get the totals for each product:
Dim products = From p In db.Products _
Where p.Category.CategoryName.StartsWith("C") _
Select p.ProductID, _
p.ProductName, _
p.UnitPrice, _
NumOrders = p.Order_Details.Count, _
Revenue = p.Order_Details.Sum(Function(details) _
details.UnitPrice * details.Quantity)
The lambda here is denoted by the "Function" keyword and it is passed to the "Sum" extension method in order to calculate the order totals for each product. In VB 9 we can also use "Aggregate" instead in this case. Additionally, we can use "Like" in the Where clause producing the following equivalent query:
Dim products = From p In db.Products _
Where p.Category.CategoryName Like"C*" _
Select p.ProductID, _
p.ProductName, _
p.UnitPrice, _
NumOrders = p.Order_Details.Count, _
Revenue = _
Aggregate detail In p.Order_Details _
Into Sum(detail.UnitPrice * detail.Quantity)
VB 9 has additional LINQ expressions that you can use instead of manually writing lambda expressions for things like Sum, Min, Max, Average, etc. I prefer the easier-to-understand VB expression syntax so I tend to use these instead. For more information on writing group and aggregate queries in VB 9 watch this video.
Enjoy!
Comments
Anonymous
September 13, 2007
PingBack from http://msdnrss.thecoderblogs.com/2007/09/13/another-way-to-linq/Anonymous
September 18, 2007
thanks , i was looking for LINQ VB samples :)Anonymous
September 18, 2007
Hi buaziz, You can also check out the VB LINQ How-Do-I videos here: http://msdn2.microsoft.com/en-us/vbasic/bb466226.aspx?wt.slv=topsectionsee#linq Cheers, -BAnonymous
July 15, 2009
The comment has been removedAnonymous
July 16, 2009
Hi Didier, Just use the aggregate clause like I show above. Is that not working for you? -BAnonymous
August 30, 2009
oooooooooh massi she is my lovely teacher