Duke
Duke

Reputation: 1923

C# LINQ sub-where

I have object

   public class OrderItem
   {
      public string idProduct { get; set; }
      public int quantity { get; set; }
      public List<WarehouseItem> WarehouseInfo = new List<WarehouseItem>();
   }

   public class WarehouseItem
   {
       public string Name{ get; set; }
       public string LocnCode{ get; set; }
   }

and i need select items which have WarehouseInfo.LocnCode == "A1"

It is doesnt work when I use something like

var items = itemList.Where(x => x.WarehouseInfo.Where(y => y.LocnCode.Equals("A1")));

Upvotes: 1

Views: 253

Answers (2)

D Stanley
D Stanley

Reputation: 152521

Your requirements could be interpreted one of three ways, so here's three solutions:

  1. Give me all OrderItems where ANY WarehouseItem has a LocnCode of "A1":

    var items = itemList.Where(i => i.WarehouseInfo.Any(w => w.LocnCode  == "A1"));
    
  2. Give me all WarehouseItems within the OrderItems that have a LocnCode of "A1":

    var items = itemList.SelectMany(i => i.WarehouseInfo)
                        .Where(w => w.LocnCode.Equals("A1"));
    
  3. Give me all OrderItems where ANY WarehouseItem has a LocnCode of "A1", and filter WarehouseInfo to only those WarehouseItems:

This can't be done in a simple Linq query because there's no way to change the contents of the existing objects. You're going to have to create new objects with the filtered values:

    var items = itemList.Where(i => i.WarehouseInfo.Any(w => w.LocnCode  == "A1"))
                        .Select(i => new OrderItem
                                     {
                                         idProduct     = i.idProduct, 
                                         quantity      = i.quantity,
                                         WarehouseInfo = i.WarehouseInfo.Where(w => w.LocnCode.Equals("A1"));
                                                                        .ToList()
                                     }
                               );

Upvotes: 3

juharr
juharr

Reputation: 32266

Try

var items = itemList.Where(x => x.WarehouseInfo.Any(y => y.LocnCode.Equals("A1")));

The Where takes a predicate that should return a bool. Any will return true if at least one item in the collection returns true for the given predicate.

Upvotes: 0

Related Questions