Enumerable.Distinct 方法 是常用的LINQ扩展方法,属于System.Linq的Enumerable方法,可用于去除数组、集合中的重复元素,还可以自定义去重的规则。
有两个重载方法:
// // 摘要: // 通过使用默认的相等比较器对值进行比较返回序列中的非重复元素。 // // 参数: // source: // 要从中移除重复元素的序列。 // // 类型参数: // TSource: // source 中的元素的类型。 // // 返回结果: // 一个 System.Collections.Generic.IEnumerable<T>,包含源序列中的非重复元素。 // // 异常: // System.ArgumentNullException: // source 为 null。 public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source); // // 摘要: // 通过使用指定的 System.Collections.Generic.IEqualityComparer<T> 对值进行比较返回序列中的非重复元素。 // // 参数: // source: // 要从中移除重复元素的序列。 // // comparer: // 用于比较值的 System.Collections.Generic.IEqualityComparer<T>。 // // 类型参数: // TSource: // source 中的元素的类型。 // // 返回结果: // 一个 System.Collections.Generic.IEnumerable<T>,包含源序列中的非重复元素。 // // 异常: // System.ArgumentNullException: // source 为 null。 public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer);
第一个方法不带参数,第二个方法需要传一个System.Collections.Generic.IEqualityComparer<T>的实现对象
1.值类型元素集合去重
List<int> list = new List<int> { 1, 1, 2, 2, 3, 4, 5, 5 }; list.Distinct().ToList().ForEach(s => Console.WriteLine(s));
执行结果是:1 2 3 4 5
2.引用类型元素集合去重
首先自定义一个Student类
public class Student { public string Name { get; private set; } public int Id { get; private set; } public string Hobby { get; private set; } public Student(string name, int id, string hobby) { this.Name = name; this.Id = id; this.Hobby = hobby; } /// <summary> /// 方便输出,重写ToString方法 /// </summary> /// <returns></returns> public override string ToString() { return string.Format("{0}\t{1}\t{2}", this.Name, this.Id, this.Hobby); } }