linq distinct或由多个属性分组

如何使用c#和Linq从下一个列表中获取result

  var pr = new List() { new Product() {Title="Boots",Color="Red", Price=1}, new Product() {Title="Boots",Color="Green", Price=1}, new Product() {Title="Boots",Color="Black", Price=2}, new Product() {Title="Sword",Color="Gray", Price=2}, new Product() {Title="Sword",Color="Green",Price=2} }; 

Result

  {Title="Boots",Color="Red", Price=1}, {Title="Boots",Color="Black", Price=2}, {Title="Sword",Color="Gray", Price=2} 

我知道我应该使用GroupByDistinct ,但要了解如何获得所需

  List result = pr.GroupBy(g => g.Title, g.Price).ToList(); //not working List result = pr.Distinct(...); 

请帮忙

它是按所需属性分组并选择:

 List result = pr.GroupBy(g => new { g.Title, g.Price }) .Select(g => g.First()) .ToList(); 

虽然新的匿名类型可以工作,但它可能更有意义,更具可读性,并且可以在您的方法之外使用,以创建自己的类型或使用元组 。 (其他时候它可能只需要使用分隔的字符串: string.Format({0}.{1}, g.Title, g.Price)

 List result = pr.GroupBy(g => new Tuple(g.Title, g.Price)) .ToList(); List result = pr.GroupBy(g => new ProductTitlePriceGroupKey(g.Title, g.Price)) .ToList(); 

至于获得你想要的结果集,提供的答案建议只返回第一个,也许这可以用于你的目的,但理想情况下你需要提供一种聚合或忽略Color方法。

例如,也许您宁愿列出所包含的颜色,不知何故:

 List result = pr .GroupBy(g => new Tuple(g.Title, g.Price)) .Select(x => new Product() { Title = x.Key.Item1, Price = x.Key.Item2, Color = string.Join(", ", x.Value.Select(y => y.Color) // "Red, Green" }) .ToList(); 

在颜色的简单字符串属性的情况下,简单地连接它们可能是有意义的。 如果你在那里有另一个实体,或者根本不想抽象出那些信息,那么最好还是让另一个实体拥有该实体类型的集合。 例如,如果您对标题和颜色进行分组,则可能需要显示平均价格或一系列价格,而只需选择每个组中的第一个就会阻止您这样做。

 List result = pr .GroupBy(g => new Tuple(g.Title, g.Price)) .Select(x => new ProductGroup() { Title = x.Key.Item1, Price = x.Key.Item2, Colors = x.Value.Select(y => y.Color) }) .ToList();