1

我有对象

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

我需要选择具有 WarehouseInfo.LocnCode == "A1" 的项目

当我使用类似的东西时它不起作用

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

2 回答 2

3

您的要求可以解释为三种方式之一,所以这里有三种解决方案:

  1. 给我所有OrderItems任何WarehouseItem有的LocnCode地方"A1"

    var items = itemList.Where(i => i.WarehouseInfo.Any(w => w.LocnCode  == "A1"));
    
  2. 给我所有WarehouseItemsOrderItem中具有 aLocnCode的s "A1"

    var items = itemList.SelectMany(i => i.WarehouseInfo)
                        .Where(w => w.LocnCode.Equals("A1"));
    
  3. 给我所有OrderItems任何WarehouseItem有 aLocnCode的地方"A1",并过滤WarehouseInfo到只有那些WarehouseItems:

这不能在简单的 Linq 查询中完成,因为无法更改现有对象的内容。您将不得不使用过滤后的值创建新对象:

    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()
                                     }
                               );
于 2013-03-25T18:53:25.520 回答
0

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.

于 2013-03-25T18:41:03.857 回答