Linq查询Where Contains()检查字符串列表

时间:2017-05-26 19:34:04

标签: c# linq

考虑以下查询:

var query = from o in this.OrderManager.LoadOrders()
            join s in this.SkuManager.LoadSkus() on o.SKU equals s.SKU
            where o.ORDER_ID == orderId
            let parcelItem = o.RPU != "Y" && o.DROP_SHIP != "Y" && s.TRUCK_SHIP != "T" && o.SKU != "ABC-123" && o.SKU != "XYZ-789" && o.SKU != "JKL-456"
            select new OrderMailLineItem
            {
                OrderId = o.ORDER_ID,
                Sku = s.SKU,
                WarehouseId = s.SITE_ID,
                QualifyingItem = qualifyingItem,
                OversizedItem = parcelItem && (s.DROP_SHIP == null)
            };

我希望能够将let parcelItem = ...行更像!o.SKU.Contains(skuList),其中:

List<string> skuList = new List<string> { "ABC-123", "XYZ-789", "JKL-456"};

3 个答案:

答案 0 :(得分:1)

您应该检查SKU是否不在列表中,而不是检查列表是否在SKU中:

let parcelItem = !skuList.Contains(o.SKU)

答案 1 :(得分:0)

!skuList.Contains(o.SKU)正是您通常会这样做的。

但如果您愿意,可以编写In运算符:

public static class ExtensionMethods
{
    public static bool In<T>(this T t, params T[] values)
        => values.Contains(t);
}

...

        let parcelItem = o.RPU != "Y" && o.DROP_SHIP != "Y" && s.TRUCK_SHIP != "T" && 
                        !o.SKU.In("ABC-123", "XYZ-789", "JKL-456")

我怀疑它是否会与Linq一起使用SQL。

答案 2 :(得分:0)

我不明白为什么这不起作用。除了SKU列表之外,您还需要检查这三个是/否标志。

var skuList = new[] { "ABC-123", "XYZ-789", "JKL-456"};
var query = from o in this.OrderManager.LoadOrders()
        join s in this.SkuManager.LoadSkus() on o.SKU equals s.SKU
        where o.ORDER_ID == orderId
        let parcelItem = o.RPU != "Y" && o.DROP_SHIP != "Y" && s.TRUCK_SHIP != "T" && skuList.Contains(o.SKU)
        select new OrderMailLineItem
        {
            OrderId = o.ORDER_ID,
            Sku = s.SKU,
            WarehouseId = s.SITE_ID,
            QualifyingItem = qualifyingItem,
            OversizedItem = parcelItem && (s.DROP_SHIP == null)
        };