One thing that LINQ seems to me lacking is the way that columns are referenced by text string. For example, I have a typical GridView configured with this sorting (DataSource bound to LINQ query in code):
<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 make sorting work, I have to use two giant Select statements in the MyGridView_Sorting event handler (to handle the upstream and downstream):
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 must be a better way to do this, right? I get the field name and sort direction from the grid - you would think that there is a way to easily pass this into a LINQ query without having to translate it across the field. Does anyone have a better way?
source
share