C#代码如下

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.Add(keySelector(element)))

        {
            yield return element;
        }
    }
}

使用方法

1、针对ID,和Name进行Distinct
var query = allProduct.DistinctBy(p => new { p.Id, p.Name });
2、仅仅针对ID进行distinct:
var query = allProduct.DistinctBy(p => p.Id);

相关文章:

  • 2021-07-02
  • 2021-11-11
  • 2021-11-26
  • 2022-12-23
  • 2022-12-23
  • 2021-07-27
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-05
  • 2021-12-11
  • 2022-01-28
  • 2022-12-23
  • 2022-12-23
  • 2021-12-13
相关资源
相似解决方案