Huma Ali
Huma Ali

Reputation: 1809

LINQ where clause condition in if

I have a class containing following properties:

public class Suborder
{
     public List<OrderLineItem> OrderLineItemList { get; set; }
     public string ProviderCode { get; set; }
}


public class OrderLineItem
{
    public List<OrderLineItem> BundleComponentList { get; set; }
    public string Product { get; set; }
}

I want to traverse through BundleComponentList to check if its any of its item has Product value equal to Shoes. I tried like this but getting error

if (suborder.OrderLineItemList.Any(x => x.Product == "Shoes") || suborder.OrderLineItemList.Where(x=>x.BundleComponentList.Any(y=>y.Product == "Shoes")))

Operator '||' cannot be applied to operands of type 'bool' and 'System.Collections.Generic.IEnumerable

What is wrong with my LINQ?

Upvotes: 0

Views: 58

Answers (3)

Elvison
Elvison

Reputation: 163

Where() does not return a boolean value but an IEnumerable and so it cannot be used in an if-clause. You should use Any() in your case.

if (suborder.OrderLineItemList.Any(x => x.Product == "Shoes") || 
    suborder.OrderLineItemList.Any(x => x.BundleComponentList.Any(y => y.Product == "Shoes")))

Please also note that the above if-clause assumes that suborder is never null.

Upvotes: 0

Yom T.
Yom T.

Reputation: 9180

I would combine lambda with LINQ for it. Much easier to read and see what's going on:

var orders = from o in suborder.OrderLineItemList
             where
               o.Product == "Shoes" ||
               o.BundleComponentList.Any(c => c.Product == "Shoes")
             select o;

bool isShoesOrder = orders.Any();

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56393

Use Any instead of Where as Where returns a sequence, not a bool.

suborder.OrderLineItemList.Any(x => x.BundleComponentList.Any(y => y.Product == "Shoes")))

Upvotes: 3

Related Questions