简体   繁体   中英

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:

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 ?

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM