动态排序在LINQ [英] dynamic sort in linq

查看:120
本文介绍了动态排序在LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下情况:



我有一个类的大约有50 fields.I列表,希望有一个组合框的用户可以根据哪个字段列表中选择将sort.For例如,如果用户排序按F1,选择F1列表中。



我不想和如果 - 排序其他每fields.I请参阅本主题:



数据绑定对象的集合或列表



<当排序的GridView -A-gridview的-时,数据绑定-A-集合或列表对象的, p>但我不能用它的答案。如何使用表达式树用于这一目的?



感谢



修改1)



据亲爱@Thom史密斯的答案我写了这个代码:

 使用(NorthwindModel1.NorthwindEntities2 ENT =新NorthwindModel1.NorthwindEntities2())
{
VAR的查询=从o在ent.Orders
,其中o.OrderID< 10257
选择o;

query.OrderBy(客户ID,SortDirection.Ascending);

GridView1.DataSource =查询;
GridView1.DataBind();
}



但它没有排序。如果我写的代码是这样的:

  GridView1.DataSource = query.OrderBy(O => o.CustomerID); 



它是排序。问题出在哪里?


解决方案

排序依据不做就地排序。它的返回的其中的的顺序计算时的进行排序。这通常是懒洋洋的,意思是:直到它被列举,它的没有即可。您当前的代码只是丢弃这个十分重要的返回值。解决方法是简单的:赶返回值:

 查询= query.OrderBy(客户ID,SortDirection.Ascending); 

请注意:同样,应用去哪儿不过滤现有数据:它会返回一个序列的枚举时的过滤。所以,如果你是过滤你有相似的:

 查询= query.Where(...); 


please consider this scenario:

I have a list of a class with about 50 fields.I want to have a Combobox that user can select according to what field list will sort.For example if user select "F1" list sort according to "F1".

I don't want to sort with if-else for every fields.I see this topic :

Sorting a gridview when databinding a collection or list of objects

but I can't use of it's answer. How I can use Expression Tree for this purpose?

thanks

Edit 1) :

According to dear @Thom Smith answer I wrote this code:

 using (NorthwindModel1.NorthwindEntities2 ent = new NorthwindModel1.NorthwindEntities2())
    {
        var query = from o in ent.Orders
                    where o.OrderID < 10257
                    select o;

        query.OrderBy("CustomerID", SortDirection.Ascending);

        GridView1.DataSource = query;
        GridView1.DataBind();
    }

but it was not sorted. if I wrote that code in this way:

GridView1.DataSource = query.OrderBy(o=>o.CustomerID);

it being sort. where is the problem?

解决方案

OrderBy does not do an in-place sort. It returns a sequence which when evaluated will be sorted. This is usually done lazily, meaning: until it is enumerated, it does nothing. Your current code simply discards this all-important return value. The fix is simple: catch the return value:

query = query.OrderBy("CustomerID", SortDirection.Ascending);

Note: similarly, applying "Where" doesn't filter the existing data: it returns a sequence that when enumerated is filtered. So if you were filtering you'd have the similar:

query = query.Where(...);

这篇关于动态排序在LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆