3

The one thing that LINQ seems to be missing for me is a way to reference columns by text string. For example, I have a typical GridView set up with sorting like this (the DataSource is bound to a LINQ query in the code-behind):

<asp:GridView ID="MyGridView" runat="server" AllowSorting="True">
    <Columns>
        <asp:BoundField DataField="field1" SortExpression="field1" HeaderText="Field 1" />
        <asp:BoundField DataField="field2" SortExpression="field2" HeaderText="Field 2" />
        <%-- etc. --%>
    </Columns>
</asp:GridView>

To get the sorting to work, I have to use two giant Select statements in the MyGridView_Sorting event handler (to handle ascending and descending):

Dim query = From t In context.MyTables

If e.SortDirection = SortDirection.Ascending Then
    Select Case e.SortExpression
        Case "field1"
            query = query.OrderBy(Function(x) x.field1)
        Case "field2"
            query = query.OrderBy(Function(x) x.field2)
        'etc.'
    End Select
Else
    Select Case e.SortExpression
        Case "field1"
            query = query.OrderByDescending(Function(x) x.field1)
        Case "field2"
            query = query.OrderByDescending(Function(x) x.field2)
        'etc.'
    End Select
End If

There has got to be a better way to do this, doesn't there? I'm getting the field name and sort direction from the grid - you'd think there would be a way to easily feed that to the LINQ query without having to translate it field by field. Anyone have a better way?

gfrizzle
  • 12,419
  • 19
  • 78
  • 104

0 Answers0