LINQ OrderBy / ThenBy带条件排序

时间:2014-03-03 18:23:54

标签: c# linq list sorting

我正在尝试按日期排序列表,然后按描述名称排序,但是我需要具有特定描述的所有元素作为每个日期的顶部元素。

示例:

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)

4 个答案:

答案 0 :(得分:7)

这一系列的排序语句将对其示例的显示方式进行排序

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

答案 1 :(得分: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();

这使您可以精确控制您认为在排序中具有更多或更少“重量”的条件。

干杯

答案 2 :(得分:1)

只需将该条件添加为中间排序顺序:

return ListOfItems.OrderBy(x => x.Date)
                  .ThenBy(x => x.Type == "Description B" ? 0 : 1)
                  .ThenBy(x => x.Type);

答案 3 :(得分:0)

如果没有定义新的排序,您可以尝试类似:

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