简体   繁体   中英

Unable to iterate and compare two lists

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

use

!costs.Any(x=>x.Sku == sku)

or even better

costs.All(x=>x.Sku != sku)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM