[英]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.