'Why DistinctBy does not contain a definition?
I have a table of product specifications I do not want duplicate elements to be displayed when displaying product specifications. I did this, but the error is displayed. Where did I go wrong?
And displays this error: 'IEnumerable' does not contain a definition
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();
}
Solution 1:[1]
DistinctBy came with .NET 6 (New LINQ APIs section). Looks like you are using lower version. You can try one of these below.
1- You can write extension on your own,
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> listItems, Func<T, TKey> groupingKey)
{
return listItems.GroupBy(groupingKey).Select(x => x.First());
}
2- Upgrade your .NET version,
3- Use GroupBy() directly,
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- Use MoreLinq to have DistinctBy()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Berkay Yaylac? |
