簡體   English   中英

無法迭代和比較兩個列表

[英]Unable to iterate and compare two lists

我有以下型號:

public class ProductRequest
{
    public List<string> Skus { get; set; }
}

public class ProductResponse
{
    public string Sku { get; set; }
    public decimal Cost { get; set; }
}

下面的代碼是方法的一部分,該方法接收ProductRequest request的輸入參數並執行LINQ查詢。 我想檢查結果列表中是否缺少原始列表中的任何sku ,但是我無法提出正確的語法。 它不喜歡!costs.Contains(sku) 不確定我在做什么錯嗎?

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

采用

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

甚至更好

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

如果要檢查任何內容,則可能要使用.Any方法。

foreach (var sku in request.Skus)
{
    if (!costs.Any(x => x.Sku == sku))
    {
        //some error handling here...
    }
}

或者您可以使用.Exists

foreach (var sku in request.Skus)
{
    if (!costs.Exists(x => x.Sku == sku))
    {
        //some error handling here...
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM