鉴于以下情况:
public class Data {
public bool Value1 { get; set; }
public bool Value2 { get; set; }
public int Value3 { get; set; }
}
var list = new List<Data> {
new Data { Value1 = true, Value2 = false, Value3 = 5}, // d1
new Data { Value1 = true, Value2 = true, Value3 = 10}, // d2
new Data { Value1 = false, Value2 = false, Value3 = 20}, // d3
new Data { Value1 = false, Value2 = true, Value3 = 30}, // d4
new Data { Value1 = false, Value2 = false, Value3 = 15} // d5
};
var orderedList = list.OrderByDescending(d => d.Value1).ThenByDescending(d => d.Value2).ThenBy(d => d.Value3);
我希望实现的目标是:d1 - d2 - d4 - d5 - d3
orderedList
中的实际结果是:d2 - d1 - d4 - d5 - d3
这是因为在d2
,Value2
和 Value1
是true
,所以它可能有意义。不过,在这个用例中,我并不关心Value1
和Value2
true
。我希望实现我的目标
Value1
的对象都是真的,在那些被排序的对象中
Value3
Value2
的所有对象都为真
由Value3
Value3
有没有可能实现这个目标?
答案 0 :(得分:4)
var orderedList = list.OrderByDescending(d => d.Value1).
ThenByDescending(d => d.Value1 || d.Value2).
ThenBy(d => d.Value3);
答案 1 :(得分:2)
以下代码可能会帮助您入门。你有三个规则,编码在代码的前三行。
var firstBit = list.Where(z => z.Value1).OrderBy(z => z.Value3);
var secondBit = list.Where(z => !z.Value1 && z.Value2).OrderBy(z => z.Value3);
var last = list.Where(z => !z.Value1 && !z.Value2).OrderBy(z => z.Value3);
var final = firstBit.Concat(secondBit).Concat(last);
Console.WriteLine(string.Join(",", final.Select(z => z.Value3)));
答案 2 :(得分:0)
您可以尝试以下
根据评论更新了代码。
var orderedVal1 = list.Where(item=>item.Value1==true).OrderBy(d => d.Value3);
var orderedVal2 = list.Where(item=>item.Value1==false && item.Value2==true).OrderBy(d => d.Value3);
var orderedVal3 = list.Where(item=>item.Value1==false && item.Value2 ==false).OrderBy(d => d.Value3);
var orderedList = orederedval1.Concat(orderedVal2).Concat(orderedVal3);