List 去除重复

来源:互联网 发布:网络黑白pdf百度云 编辑:程序博客网 时间:2024/06/15 18:52

// 扩展IEnumerable<T>
static class ExternEnumerable {
        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;
                }
            }
        }
    }
     
    // 筛选去重调用
     IEnumerable<User> ie = list; // 先转换为IEnumerable接口类型
     ie=ie.DistinctBy<User,string>(u=>u.DatasName+"|"+u.DatasType+"|"+u.DatasValue);
0 0
原创粉丝点击