简体   繁体   English

LINQ OrderBy / ThenBy带条件排序

[英]LINQ OrderBy / ThenBy with conditional sorting

I am trying to sort a list by date and then by description name, however I need all elements with a certain description to be the top element for each date. 我试图按日期排序列表,然后按描述名称排序,但是我需要具有特定描述的所有元素作为每个日期的顶部元素。

Example: 例:

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"

How I need it sorted is by date and description but also all Description B elements at top of list within each date. 我需要它如何排序是按日期和描述,但也是每个日期内列表顶部的所有描述B元素。 Like this, 像这样,

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"

I've tried doing this with LINQ but I am not sure if it can be done as a single query. 我试过用LINQ做这个,但我不确定它是否可以作为单个查询完成。

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

This series of ordering statements will sort it how your example shows 这一系列的排序语句将对其示例的显示方式进行排序

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

A more complete solution would be to implement your own IComparer like this: 更完整的解决方案是实现您自己的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));
    }
}

Then you can use it like so: 然后你可以像这样使用它:

var sorted = lst.OrderBy(x => x.Date).ThenBy(x => x.Description, new CustomComparer()).ToList();

This gives you fine control over what condition you consider as having more or less "weight" in the sort. 这使您可以精确控制您认为在排序中具有更多或更少“重量”的条件。

Cheers 干杯

Just add that condition as an intermediate sort order: 只需将该条件添加为中间排序顺序:

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

Without defining a new sort, you could try something like: 如果没有定义新的排序,您可以尝试以下方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM