簡體   English   中英

如何在具有兩個屬性的對象列表中檢查具有相同屬性的所有對象是否也具有相同的其他屬性?

[英]How to check if in a list of Objects with two properties, all Objects with one equal property also have the same other property?

我有一個ProductList<Product> productListList<Product> productList ,其中:

public class Product
{
     int ProductId { get; set; }
     decimal Price { get; set; }
}

如何檢查此productList所有具有ProductId ProductPrice是否也相同?

我發現這可行:

bool result = productCheckList.GroupBy(p => p.ProductId).Any(gr => 
                     gr.Distinct().ToList().Count > 1)`;

但是我也想找出一個是否不相似, 哪些不相似。

所以當我有一個這樣的列表:

var list = new List<Product>
list.Add(new Product { ProductId = 1, Price = 2m }
list.Add(new Product { ProductId = 1, Price = 1m }

我希望該方法返回false,並顯示ProductId = 1。

這些組包含產品,而不是產品的價格,因此您需要確定價格:

bool result =
  productCheckList.GroupBy(p => p.ProductId)
  .Any(gr => gr.Select(pr => pr.Price).Distinct().Count() > 1);

要獲得價格不同的產品組:

List<IGrouping<int, Product>> result =
  productCheckList.GroupBy(p => p.ProductId)
  .Where(gr => gr.Select(pr => pr.Price).Distinct().Count() > 1)
  .ToList();

暫無
暫無

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

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