使用条件排序的LINQ OrderBy / ThenBy

3

我正在尝试按日期和描述名称对列表进行排序,但是我需要每个日期中具有特定描述的所有元素都位于顶部元素。

例如:

01-02-2014 "Description A"
01-02-2014 "Description B"
01-02-2014 "Description C"
01-02-2014 "Description D"
01-02-2014 "Description E"

02-02-2014 "Description A"
02-02-2014 "Description B"
02-02-2014 "Description C"
02-02-2014 "Description D"
02-02-2014 "Description E"

我需要按照日期和描述进行排序,但是在每个日期下,所有描述为B的元素都应该排在列表顶部。就像这样,
01-02-2014 "Description B" <-- Top (Rest below is still sorted ascending)
01-02-2014 "Description A"
01-02-2014 "Description C"
01-02-2014 "Description D"
01-02-2014 "Description E"

02-02-2014 "Description B" <-- Top (Rest below is still sorted ascending)
02-02-2014 "Description A"
02-02-2014 "Description C"
02-02-2014 "Description D"
02-02-2014 "Description E"

我尝试使用LINQ来完成这个操作,但不确定是否可以作为单个查询完成。

return ListOfItems.OrderByDescending(x => x.Date).ThenBy(x => x.Type)

由于这不是自然排序,您需要引入一个新的属性或列,在其中优先考虑您想要置顶的项目。然后,您可以在按描述名称排序之前使用该值进行排序。 - Yuck
4个回答

8
这一系列的排序语句将按照你的示例对其进行排序。
return ListOfItems.OrderBy(x => x.Date)
                  .ThenByDescending(x => x.Type == "Description B")
                  .ThenBy(x => x.Type);

4

更完整的解决方案是实现自己的 IComparer,如下所示:

class CustomComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        if (x == y)
            return 0;
        else if (x == "Description B")
            return -1;
        else
            return (x.CompareTo(y));
    }
}

然后,您可以像这样使用它:
var sorted = lst.OrderBy(x => x.Date).ThenBy(x => x.Description, new CustomComparer()).ToList();

这使得你能够精细控制在排序中哪些条件被认为具有更高或更低的“权重”。祝好!

1
只需将该条件添加为中间排序条件即可:
return ListOfItems.OrderBy(x => x.Date)
                  .ThenBy(x => x.Type == "Description B" ? 0 : 1)
                  .ThenBy(x => x.Type);

1
为什么要使用三元运算符?你可以使用“!=”进行否定,或者只是使用“ThenByDescending”,这两种方法都更标准。 - Andrew Coonce
3
@AndrewCoonce 因为我不喜欢记住 true/false 排序的方式。 - D Stanley

0

不需要定义新的排序方式,你可以尝试这样做:

return ListOfItems.OrderByDescending(x => x.Date)
                  .ThenByDescending(x => x.Type == "Description B");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接