ASP.net gridview sorting with linq result

2019-08-28 09:34发布

问题:

up till now I have a linq query that fills a datagrid perfectly with filterconditions. however, when I try to implement sorting I fail.

I have the following code behind. it catches the start of the sort.

protected void gvServers_Sorting(object sender, GridViewSortEventArgs e)
{
    if (e.SortDirection == SortDirection.Ascending)
    {
        SortDataAsc(e.SortExpression);
    }
    else if (e.SortDirection == SortDirection.Descending)
    {
        SortDataDesc(e.SortExpression);
    }
}

in these submethods I'd want to hendle the sorting of each possible sorting expression. however, when I try to use the data that is already in the gridview it won't allow me to linq it with an orderby

private void SortDataAsc(string p)
{
    var data = gvServers.DataSource;
    switch (p)
    {
        case "domain":
            var sorted = data.nothinghappenshere
        default:
            break;
    }
}

as you can see pointing to the nothinghappenshere I cannot sort the data (proabaly because it's a var).

What I've read online is that you can just get the data from the gridview as I try to do in SortDataAsc(), but it doesn't seem to work that way.

I simply want to order by a certain field in my resultset (which is in this case an anonymous class derived from a join)

回答1:

Well, it's because DataSource is weakly typed.

If you cast it to IEnumerable<YourDataType> it should be fine. However, note that OrderBy and OrderByDescending don't sort in place - you'd have to order the data and then reassign the DataSource.

You say that your data type as an anonymous type - you'll have to change that, I'm afraid. Anonymous types can only (easily) be used in a strongly typed way in single method - you can't specify the name later on, so you can't refer to the same properties etc.

It's not terribly hard to convert an anonymous type into a named one though. Here's an answer giving an example.