Tuesday, 21 May 2013

SQL-like queries for your variables - .net LINQ

Got a list, collection, DataGridView full of data from your database, and you'd like to query that in-memory data without going back to the database itself? I recommend taking a look a LINQ Query Expressions if you haven't already.

With a simple code block, you can treat an IEnumerable<T> or IQueryable<T> collection as a data source and get results fast!

Here we iterate through a VB.net DGV (regardless of Option Strict), showing how to use an initial Select to convert the long-winded cell references into more descriptive names of your choice, and then Select again (with grouping and ordering in this case) as required  :

Dim test = From row In DataGridView1.Rows.Cast(Of DataGridViewRow)()
    Where Not row.IsNewRow
    Select num1 = CDbl(row.Cells(0).Value), num2 = CDbl(row.Cells(1).Value)
    Group By num1 Into f1_Distinct = Min(num1), f2_Distinct = Max(num2)
    Select num1 = f1_Distinct, num2 = f2_Distinct
    Order By num1
If test.Count > 0 then MsgBox(test(0).num1)

That's a lot less code that doing it the hard way! Does this whet your appetite to discover more? :)

No comments:

Post a Comment