用于Linq的去重 Distinct

        /// <summary>
        /// 用于Linq的去重,扩展方法需要放到静态类中
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="source"></param>
        /// <param name="keySelector"></param>
        /// <returns></returns>
        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;
                }
            }
        }

调用方法:
 list.DistinctBy(tmp => new { tmp.CountryName, tmp.VisaTypeName });




posted @ 2016-04-19 18:00  cn_king  阅读(960)  评论(0编辑  收藏  举报