linq 的Distinct 扩展方法.

< ![CDATA[
    List<miniclass> classs = new List<miniclass>();
            classs.Add(new miniclass()
                {
                    token = "1",
                    id = "1"
                });

            classs.Add(new miniclass()
            {
                token = "2",
                id = "1"
            });
            classs.Add(new miniclass()
            {
                token = "13",
                id = "2"
            });

            var dx = classs.DistinctBy(x => x.id);

           
            Console.ReadKey();

dx就选出来2条.内容.根据x.id.

  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;
        }
      }
    }

 

]]>

你可能感兴趣的:(distinct)