views:

3199

answers:

2

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?

+4  A: 

See this question and my subsequent answer about creating Dynamic LINQ queries

Geoff
I was hoping for a better "built in" alternative, but this is probably as good as it gets for now. I suspect something will be baked into future LINQ releases though.
gfrizzle
+2  A: 

You might want to check out this article entitled, Self Sorting GridView with LINQ Expression Trees

Thedric Walker