LINQ - 对多列进行排序

时间:2017-02-27 18:04:31

标签: linq sorting multiple-columns

我有一个包含以下值的集合:

double latitude= addresses.get(0).getLatitude();
            double longitude= addresses.get(0).getLongitude();

有没有办法使用LINQ以下面的排序方式获取输出?

ID | OtherId
1    0
2    0
3    1
3    2
3    3
4    1
4    2
4    3
5    0
6    0

1 个答案:

答案 0 :(得分:0)

您需要使用OrderBy和ThenBy:

我没有试过这个,但因为你的最后两行“乱序”,你需要先按(不)特定值排序,然后按列排序。它会是这样的:

var sorted = table
             .Where(x => x.SomeColumn == someValue)
             .OrderBy(x => x.ID != 5)
             .ThenBy(x => x.ID != 6)
             .ThenBy(x => x.OtherId)
             .ThenBy(x => x.ID)
             .ToList();

如果您不想按特定值排序,则需要执行2次查询和联合:

var valueAtWhichSortingLogicChanges = 4;
var sorted = table
             .Where(x => x.ID <= valueAtWhichSortingLogicChanges)
             .OrderBy(x => x.OtherId)
             .ThenBy(x => x.ID)
             .ToList();

sorted.AddRange(table
             .Where(x => x.ID > valueAtWhichSortingLogicChanges)
             .OrderBy(x => x.OtherId)
             .ThenBy(x => x.ID)
             .ToList());