PixelPaul
PixelPaul

Reputation: 2767

Linq query where Contains() checks for list of strings

Consider the Following Query:

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)
            };

I would like to be able to write the line let parcelItem = ... to be more like !o.SKU.Contains(skuList) where:

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

Upvotes: 0

Views: 51

Answers (3)

Derpy
Derpy

Reputation: 1528

I don't see why this wouldn't work. You would just need to check those three Yes/No flags in addition to your SKU list.

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)
        };

Upvotes: 0

!skuList.Contains(o.SKU) is exactly how you'd usually do it.

But you could write an In operator, if you like:

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")

I doubt that'll work with Linq to SQL though.

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

You should check whether SKU is not in list instead of checking whether list is in SKU:

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

Upvotes: 1

Related Questions