为什么 DistinctBy 不包含定义?

Why DistinctBy does not contain a definition?

我有 table 的产品规格 我不希望在显示产品规格时显示重复的元素。我这样做了,但显示错误。我哪里错了?

并显示此错误: 'IEnumerable' 不包含定义

 private static List<ProductPropertiesQueryModel> 
  MapProductProperties(List<ProductProperties> ProductProperties)
    {
       return ProductProperties
        .Select(x=>new ProductPropertiesQueryModel
        {
           ProductId =x.ProductId,
           Color =x.Color,
           Size=x.Size
        }).DistinctBy(r=>r.Color).ToList();                      
    }

DistinctBy came with .NET 6新的 LINQ API 部分)。看起来您使用的是较低版本。您可以尝试以下其中一项。

1-可以自己写扩展,

public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> listItems, Func<T, TKey> groupingKey)
{
     return listItems.GroupBy(groupingKey).Select(x => x.First());
}

2- 升级您的 .NET 版本,

3-直接使用GroupBy()

private static List<ProductPropertiesQueryModel> MapProductProperties(List<ProductProperties> ProductProperties)
{
       return ProductProperties
        .Select(x=>new ProductPropertiesQueryModel
        {
           ProductId =x.ProductId,
           Color =x.Color,
           Size=x.Size
        }).GroupBy(x => x.Color).Select(x => x.First()).ToList();                 
}

4- 使用MoreLinq得到DistinctBy()