[英]How to check if in a list of Objects with two properties, all Objects with one equal property also have the same other property?
我有一個Product
的List<Product> productList
的List<Product> productList
,其中:
public class Product
{
int ProductId { get; set; }
decimal Price { get; set; }
}
如何檢查此productList
所有具有ProductId
Product
的Price
是否也相同?
我發現這可行:
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.