Reputation: 1923
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
Reputation: 152521
Your requirements could be interpreted one of three ways, so here's three solutions:
Give me all OrderItems
where ANY WarehouseItem
has a LocnCode
of "A1"
:
var items = itemList.Where(i => i.WarehouseInfo.Any(w => w.LocnCode == "A1"));
Give me all WarehouseItem
s within the OrderItem
s that have a LocnCode
of "A1"
:
var items = itemList.SelectMany(i => i.WarehouseInfo)
.Where(w => w.LocnCode.Equals("A1"));
OrderItems
where ANY WarehouseItem
has a LocnCode
of "A1"
, and filter WarehouseInfo
to only those WarehouseItem
s: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
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