gpt4 book ai didi

c# - 编写 Linq Where 语句的更好方法

转载 作者:行者123 更新时间:2023-11-30 20:34:25 25 4
gpt4 key购买 nike

我对 Linq 查询中的一些多重过滤器感到困惑。

像这样:

var OrderList = (from o in db.Order
where ( o.OrderType == 1 &&
(( (o.Status & 1) != 0) || ((o.Status & 2) != 0)) )
|| ( o.OrderType == 2 &&
(( (o.Status & 3) != 0) || ((o.Status & 4) != 0)) )
orderby o.OrderID descending
select new
{
Name = o.Name
}).ToList();

Linq 中的过滤器看起来丑陋且不易阅读。

有更好的方法来重写它吗?

最佳答案

假设 Status 是一个数值类型(如 intuintlong 等。)并且没有 & 运算符的自定义实现,& 对其操作数执行按位与

所以 ((o.Status & 1) != 0) || ((o.Status & 2) != 0)(o.Status & 3) != 0 相同。它仅测试是否至少设置了两个最低有效位之一。 (注意 3 的位是 0011)。

因此 (o.Status & 3) != 0) || (o.Status & 4) != 0(o.Status & 7) != 0 相同(7 的位是 0111).

因此您可以将条件简化为:

 (o.OrderType == 1 && (o.Status & 3) != 0) ||
(o.OrderType == 2 && (o.Status & 7) != 0)

但这只是一种简化......可读性取决于读者的眼睛。为 Status 字段使用 enum 可能是合适的:

[Flags]
public enum States
{
FirstBit = 1, // use self-explaining names here
SecondBit = 2,
ThirdBit = 4
}

// condition
(o.OrderType == 1 && (o.Status.HasFlag(States.FirstBit) || o.Status.HasFlag(States.SecondBit)) ||
(o.OrderType == 2 && (o.Status.HasFlag(States.FirstBit) || o.Status.HasFlag(States.SecondBit) || o.Status.HasFlag(States.ThirdBit)))

这更长,但如果名称是不言自明的,则可能更具可读性。

关于c# - 编写 Linq Where 语句的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39223906/

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