如何使用LINQ载有()找到枚举列表?如何使用、列表、LINQ

2023-09-06 23:12:44 作者:爺傷風敗俗

我有一个名为枚举 OrderStatus ,它包含各种状态,一个订单可能有:

I have an enum called OrderStatus, and it contains various statuses that an Order can be in:

创建 待定 在等待 有效 有效 加工 已完成

我想要做的就是创建一个LINQ语句会告诉我,如果OrderStaus是有效的,主动,处理或已完成。

What I want to do is create a LINQ statement that will tell me if the OrderStaus is Valid, Active, Processed or Completed.

现在我有这样的:

var status in Order.Status.WHERE(status => 
      status.OrderStatus == OrderStatus.Valid || 
      status.OrderStatus == OrderStatus.Active|| 
      status.OrderStatus == OrderStatus.Processed|| 
      status.OrderStatus == OrderStatus.Completed)

这样的作品,但它很罗嗦。有没有办法将其转换为一个包含()语句,并缩短了一下?

That works, but it's very "wordy". Is there a way to convert this to a Contains() statement and shorten it up a bit?

推荐答案

肯定的:

var status in Order.Status.Where(status => new [] {
        OrderStatus.Valid, 
        OrderStatus.Active, 
        OrderStatus.Processed,
        OrderStatus.Completed
    }.Contains(status.OrderStatus));

您也可以定义一个扩展方法在()将接受对象和一个参数数组,基本上包装了包含功能:

You could also define an extension method In() that would accept an object and a params array, and basically wraps the Contains function:

public static bool In<T>(this T theObject, params T[] collection)
{
    return collection.Contains(theObject);
}

这允许你指定在多个SQL十岁上下的方式条件:

This allows you to specify the condition in a more SQL-ish way:

var status in Order.Status.Where(status => 
    status.OrderCode.In(
        OrderStatus.Valid, 
        OrderStatus.Active, 
        OrderStatus.Processed,
        OrderStatus.Completed));

记者了解到,并非所有的LINQ提供像他们的lambda表达式定义扩展的方法。 NHibernate的2.1,例如,将无法正确翻译在()函数,但载有()的作品就好了。对LINQ 2的对象都没有问题。

Understand that not all Linq providers like custom extension methods in their lambdas. NHibernate 2.1, for instance, won't correctly translate the In() function, but Contains() works just fine. For Linq 2 Objects, no problems.