Reputation: 2767
I have the following models:
public class ProductRequest
{
public List<string> Skus { get; set; }
}
public class ProductResponse
{
public string Sku { get; set; }
public decimal Cost { get; set; }
}
The code below is part of a method that receives an input parameter of ProductRequest request
and executes a LINQ query. I want to to check if any sku
from the original list is missing from the results list, but I am unable to come up with the proper syntax. It does not like the line !costs.Contains(sku)
. Not sure what I am doing wrong?
List<ProductResponse> costs = (from x in this.SkuManager.GetSkusBySkuNumber(request.Skus.ToList())
select new ProductCostResponse
{
Sku = x.Sku,
Cost = x.Cost
}).ToList();
foreach (var sku in request.Skus)
{
if (!costs.Contains(sku))
{
//some error handling here...
}
}
Upvotes: 0
Views: 50
Reputation: 5943
If you're checking for any then you may want to use the .Any
method.
foreach (var sku in request.Skus)
{
if (!costs.Any(x => x.Sku == sku))
{
//some error handling here...
}
}
Or you could use .Exists
foreach (var sku in request.Skus)
{
if (!costs.Exists(x => x.Sku == sku))
{
//some error handling here...
}
}
Upvotes: 1
Reputation: 9679
use
!costs.Any(x=>x.Sku == sku)
or even better
costs.All(x=>x.Sku != sku)
Upvotes: 1