I hope I've get what you want. I've simulated your PurchaseOrder
with an array of dictionaries and I suppose, that formal parameter y
in your lambda expression is derived from IDictionary
, because I can see such expression y["distributedOrderLineId"]
. Please correct me if I'm wrong in my assumptions.
The solution is to check whether key is set by calling order.ContainsKey("id")
. You can see the example below
var firstItem = new Dictionary<string, string>{{"id", "11"}};
var secondItem = new Dictionary<string, string>{{"id", "12"}};
var thirdItem = new Dictionary<string, string>(); // id is not set, as distributedOrderLineId in your example
var fourthItem = new Dictionary<string, string>{{"id", "14"}};
var PurchaseOrder = new [] {firstItem, secondItem, thirdItem, fourthItem};
var quantity = 4;
var orderID = 12;
var distributionsLeft = quantity - 1 - PurchaseOrder.Where(order => order.ContainsKey("id") && int.Parse(order["id"]) == orderID).Count();
Console.WriteLine (distributionsLeft);
Edit: Could you please try to use next query, just to see if it work? We can then try to do some optimizations if it works fine.
PurchaseOrder.Where(y => y.OrderProperties.Any(z => z.Key == "distributedOrderLineId"))
.ToList()
.Where(y => y["distributedOrderLineId"] == ol.OrderLineId.ToString())
.Count();
Optimized version: I've tried to optimize version given above from performance and readability points of view, but note - I cold be wrong, because I haven't run that query. I've changed it only by analyzing uCommerce documentation regarding OrderLine and OrderProperty. Also note, that I've used different names for formal parameters in lambdas - just to get rid of mess with y and z.
string orderLineId = ol.OrderLineId.ToString();
PurchaseOrder
.Count(order => order.OrderProperties.Any(property => property.Key == "distributedOrderLineId" && property.Value == orderLineId));