PixelPaul
PixelPaul

Reputation: 2767

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

Upvotes: 0

Views: 50

Answers (2)

Grizzly
Grizzly

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

Maksim Simkin
Maksim Simkin

Reputation: 9679

use

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

or even better

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

Upvotes: 1

Related Questions