使用LINQ进行任意排序 [英] Use LINQ for arbitrary sorting

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

问题描述

假设我们有一个实体,其属性为att1和att2,其中att1可以具有值a,b,c,而att2可以具有值1,2,3.是否可以使用LINQ,以便我们可以通过应用任意排序规则来对集合中的项目进行排序,而无需实现IComparable.我面临的一个问题是,业务需要在集合中的某些屏幕上以一种方式对项目中的项目进行排序,而在其他屏幕上则以其他方式来对其进行排序.例如,rule可以声明需要对项目进行排序,以便首先列出"b",然后列出"a",然后列出"c",在每个组中,首先列出"3​​",然后列出"1",然后列出"2".

Let's say we have an entity that has attributes att1 and att2, where att1 can have values a,b,c and att2 can have values 1,2,3. Is it possible to use LINQ so that we can sort items in the collection by applying arbitrary sorting rule without implementing IComparable. I am facing an issue were business requires that on some screens items in the collection be sorted one way and in other screens some other way. For example rule can state that items need to be sorted so that "b" is listed first, then "a", then "c" and within each group, "3" is first, then "1" then "2".

推荐答案

好的.您可以将OrderBy与一个谓词一起使用,该谓词或多或少地返回您所希望的任意种类的排序顺序".例如:

Sure. You can use OrderBy with a predicate that returns more or less whatever kind of arbitrary "sort order" you please. For example:

objectsWithAttributes.OrderBy(x =>
{
    // implement your "rules" here -- anything goes as long as you return
    // something that implements IComparable in the end.  this code will sort
    // the enumerable in the order 'a', 'c', 'b'

    if (x.Attribute== 'a')
        return 0;
    else if (x.Attribute== 'c')
        return 1;
    else if (x.Attribute== 'b')
        return 2;
}).ThenBy(x =>
{
    // implement another rule here?
});

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

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