Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用LINQ进行任意排序_Linq_Sorting_Entities - Fatal编程技术网

使用LINQ进行任意排序

使用LINQ进行任意排序,linq,sorting,entities,Linq,Sorting,Entities,假设我们有一个具有属性att1和att2的实体,其中att1可以有值a、b、c,att2可以有值1、2、3。是否可以使用LINQ,以便我们可以通过应用任意排序规则对集合中的项进行排序,而无需实现IComparable。我面临的一个问题是,业务部门要求在某些屏幕上以一种方式对集合中的项目进行排序,而在其他屏幕上以另一种方式对项目进行排序。例如,规则可以说明需要对项目进行排序,以便首先列出“b”,然后列出“a”,然后列出“c”,并且在每个组中,“3”首先列出,然后列出“1”,然后列出“2” 当然。您

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

当然。您可以使用带有谓词的
OrderBy
,该谓词或多或少地返回任意类型的“排序顺序”。例如:

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?
});