将布尔值添加到“选择新的”Linq查询

时间:2017-05-26 15:06:44

标签: c# linq

我正在尝试向Linq查询添加一个布尔值(InStock),它根据条件设置一个值,但是我收到一个错误:

The name 'Any' does not exist in the current context. Cannot resolve symbol 'Any1'

不确定这里的语法是什么?

var query = from o in Orders
            join i in OrderItems on o.SKU equals i.SKU
            where o.OrderId == orderId
            select new OrderObject
            {
                Id = o.OrderId,
                WarehouseQty = i.AvailableQty,
                Sku = i.Sku,
                InStock = Any(x => x.AvailableQty > 0)  //<--need to assign boolean here

            };

2 个答案:

答案 0 :(得分:1)

  

如果AvailableQty是&gt; 0,然后将InStock设置为true

好吧,然后使用

var query = from o in Orders
            join i in OrderItems on o.SKU equals i.SKU
            where o.OrderId == orderId
            select new OrderObject
            {
                Id = o.OrderId,
                WarehouseQty = i.AvailableQty,
                Sku = i.Sku,
                InStock = i.AvailableQty > 0
            };

无需使用用于搜索其他集合的Enumerable.Any

答案 1 :(得分:1)

您可能希望使用InStock = i.AvailableQty > 0,如下所示:

var query = from o in Orders
            join i in OrderItems on o.SKU equals i.SKU
            where o.OrderId == orderId
            select new OrderObject
            {
                Id = o.OrderId,
                WarehouseQty = i.AvailableQty,
                Sku = i.Sku,
                InStock = i.AvailableQty > 0
            };

但是,使用 WarehouseQty属性似乎是多余的。为什么不在您的班级中添加只读属性:

public class OrderObject
{
    //snip

    public bool InStock => WarehouseQty > 0;
}