linq不同于或由多个性质组成

本文关键字:不同于 linq | 更新日期: 2024-09-22 01:37:19

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

 var pr = new List<Product>()
   {
       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<Product> result = pr.GroupBy(g => g.Title, g.Price).ToList(); //not working
   List<Product> result  = pr.Distinct(...);

请帮助

linq不同于或由多个性质组成

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

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

虽然新的匿名类型可以工作,但在方法之外创建自己的类型或使用Tuple可能会更有意义、更可读、更易消耗。(其他情况下,只需使用分隔字符串即可:string.Format({0}.{1}, g.Title, g.Price)

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

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

例如,也许你更愿意列出所包含的颜色,不知何故:

List<Product> result = pr
                     .GroupBy(g => new Tuple<string, decimal>(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<ProductGroup> result = pr
                     .GroupBy(g => new Tuple<string, decimal>(g.Title, g.Price))
                     .Select(x => new ProductGroup()
                             { 
                                  Title = x.Key.Item1, 
                                  Price = x.Key.Item2,
                                  Colors = x.Value.Select(y => y.Color)
                             })
                     .ToList();

如果您想将一些逻辑抽象为可重用的扩展方法,可以添加以下内容:

public static IEnumerable<TSource> DistinctBy<TSource, TKey>
    (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    HashSet<TKey> seenKeys = new HashSet<TKey>();
    foreach (TSource element in source)
    {
        if (!seenKeys.Contains(keySelector(element)))
        {
            seenKeys.Add(keySelector(element));
            yield return element;
        }
    }
}

这将适用于单个属性和复合属性,并返回第一个匹配元件

// distinct by single property
var productsByTitle = animals.DistinctBy(a => a.Title);
// distinct by multiple properties
var productsByTitleAndColor = animals.DistinctBy(a => new { a.Title, a.Color} );

这种方法的一个好处(而不是先按+分组)是,如果以后的条件不强制您循环整个集合,您可以返回一个yieldable枚举

进一步阅读:linq查询从对象列表中返回不同的字段值