简体   繁体   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?

I have a list of Product s List<Product> productList , where: 我有一个ProductList<Product> productListList<Product> productList ,其中:

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

How do I check if in this productList all Product s with the ProductId also have the same Price ? 如何检查此productList所有具有ProductId ProductPrice是否也相同?

I found that this works: 我发现这可行:

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

But I also want to find out if one is not similar, which ones are not. 但是我也想找出一个是否不相似, 哪些不相似。

So when I have a List like this: 所以当我有一个这样的列表:

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

I want the method to return false, and show ProductId = 1. 我希望该方法返回false,并显示ProductId = 1。

The groups contains the products, not the prices for the products, so you would need to get the prices out: 这些组包含产品,而不是产品的价格,因此您需要确定价格:

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

To get the product groups where the prices differs: 要获得价格不同的产品组:

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