Results 1 to 3 of 3

Thread: [RESOLVED] LINQ : combine two selects like a SQL CTE?

Threaded View

  1. #3

    Thread Starter
    Lively Member
    Join Date
    Apr 2011
    Posts
    75

    Re: LINQ : combine two selects like a SQL CTE?

    Ah, brilliant, many thanks!
    What a great way to play with data, impressive stuff

    The Wrong Way

    At first I couldn't get this to work
    Code:
    Dim tst = From row As DataGridViewRow In DataGridView1.Rows
    because of an error : Option Strict On disallows implicit conversions from 'Object' to 'System.Windows.Forms.DataGridViewRow'

    So to work around that, I toyed with a user-defined variable type (like a Pascal 'record') and a list of those, manually adding to the list from a loop around the DGV.

    Code:
        Private Structure MyRow
            Property field1 As Double
            Property field2 As Double
        End Structure
    
            Dim myList As IList(Of MyRow)
            myList = New List(Of MyRow)
            For cnt As Integer = 0 To DataGridView1.Rows.Count - 1
                If Not (DataGridView1.Rows(cnt).IsNewRow) Then
                    myList.Add(New myRow() With
                       {.field1 = CDbl(DataGridView1.Rows(cnt).Cells(0).Value),
                        .field2 = CDbl(DataGridView1.Rows(cnt).Cells(1).Value)
                       })
                End If
            Next
    
            ' LINQ query
            Dim Results = From Rows In myList
                               Group By ... Into ...
                               Select ......
                               Order By .... etc
    The Better Way

    With a simple Cast, and the help given above, here's the easy way.
    Much better now I can do this all in one go!
    e.g....
    Code:
            Dim tst = From row In DataGridView1.Rows.Cast(Of DataGridViewRow)()
                            Where Not row.IsNewRow
                            Select field1 = CDbl(row.Cells(0).Value), field2 = CDbl(row.Cells(1).Value)
                            Group By field1 Into f1_Distinct = Min(field1), f2_Distinct = Max(field2)
                            Select field1 = f1_Distinct, field2 = f2_Distinct
                            Order By field1
    
    
            If tst.Count > 0 then MsgBox(tst(0).field1)
    Last edited by geek648; Mar 6th, 2013 at 06:36 AM. Reason: extra info given, hope it's helpful

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