gpt4 book ai didi

C# LINQ 顺序错误?

转载 作者:太空狗 更新时间:2023-10-30 01:03:05 25 4
gpt4 key购买 nike

我有一个我想要订购的对象列表,但我不知道如何使用 LINQ 来完成它,也许我在想 LINQ 以不同的方式工作。

我可以通过使用示例中的 where 子句简单地解决问题,但我想了解发生了什么。

谁能解释一下为什么我不能在“值”变量中得到预期的结果?

谢谢

预期结果

[列表“值”中对象的顺序]:

new MyClass{Ordinal = 1, A = true, B = Status.Released, C = 3}
new MyClass{Ordinal = 0, A = true, B = Status.Released, C = 2}
new MyClass{Ordinal = 4, A = true, B = Status.Skipped, C = 5}
new MyClass{Ordinal = 2, A = true, B = Status.Skipped, C = 4}
new MyClass{Ordinal = 3, A = false, B = Status.Skipped, C = 1}

示例

public class Program
{
static void Main(string[] args)
{
var lst = new List<MyClass>{
new MyClass{Ordinal = 0, A = true, B = Status.Released, C = 2},
new MyClass{Ordinal = 1, A = true, B = Status.Released, C = 3},
new MyClass{Ordinal = 2, A = true, B = Status.Skipped, C = 4},
new MyClass{Ordinal = 3, A = false, B = Status.Skipped, C = 1},
new MyClass{Ordinal = 4, A = true, B = Status.Skipped, C = 5}
};


var workaround = lst.Where(i => i.B != Status.Skipped && i.B != Status.Cancelled)
.OrderByDescending(i => i.A)
.ThenByDescending(i => i.C)
.ToList();

var values = lst.OrderByDescending(i => i.A)
.ThenBy(i => i.B == Status.Skipped && i.B == Status.Cancelled)
.ThenByDescending(i => i.C)
.ToList();

/* order of the objects in "values"
new MyClass{Ordinal = 4, A = true, B = Status.Skipped, C = 5}
new MyClass{Ordinal = 2, A = true, B = Status.Skipped, C = 4}
new MyClass{Ordinal = 1, A = true, B = Status.Released, C = 3}
new MyClass{Ordinal = 0, A = true, B = Status.Released, C = 2}
new MyClass{Ordinal = 3, A = false, B = Status.Skipped, C = 1}
*/
}
}

public class MyClass
{
public int Ordinal { get; set; }

public bool A { get; set; }
public Status B { get; set; }
public int C { get; set; }
}

public enum Status
{
Unknown,
Released,
Cancelled,
Received,
Processing,
Succeeded,
Failed,
Skipped
}

最佳答案

lambda 表达式

i => i.B == Status.Skipped && i.B == Status.Cancelled

用于 ThenBy 函数将 MyClass 的每个实例映射到 false,假设 Status.SkippedStatus.Cancelled 是不同的值;这导致没有有用的排序。也许你的意思是

i => i.B != Status.Skipped && i.B != Status.Cancelled

将状态为 Status.SkippedStatus.Cancelled 的条目排到底部。

关于C# LINQ 顺序错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30803353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com