下表列出了LINQ中可用的所有Set运算符。
集合运算符 | 用法 |
---|---|
Distinct | 返回集合中的非重复值。 |
Except | 返回两个序列之间的差,这意味着一个集合中的元素不出现在第二个集合中。 |
Intersect | 返回两个序列的交集,即同时出现在两个集合中的元素。 |
Union | 返回两个序列中的唯一元素,这意味着出现在两个序列中的唯一元素。 |
Distinct扩展方法从给定集合返回一个新的唯一元素集合。
IList<string> strList = new List<string>(){ "One", "Two", "Three", "Two", "Three" }; IList<int> intList = new List<int>(){ 1, 2, 3, 2, 4, 4, 3, 5 }; var distinctList1 = strList.Distinct(); foreach(var str in distinctList1) Console.WriteLine(str); var distinctList2 = intList.Distinct(); foreach(var i in distinctList2) Console.WriteLine(i);
One Two Three 1 2 3 4 5
Distinct扩展方法不比较复杂类型对象的值。为了比较复杂类型的值,需要实现IEqualityComparer<T>接口。在下面的示例中,StudentComparer类实现IEqualityComparer<Student>来比较Student<objects。
public class Student { public int StudentID { get; set; } public string StudentName { get; set; } public int Age { get; set; } } class StudentComparer : IEqualityComparer<Student> { public bool Equals(Student x, Student y) { if (x.StudentID == y.StudentID && x.StudentName.ToLower() == y.StudentName.ToLower()) return true; return false; } public int GetHashCode(Student obj) { return obj.StudentID.GetHashCode(); } }
现在,您可以在Distinct()方法中传递上述StudentComparer类的对象作为参数来比较Student对象,如下所示。 示例:C#中的Distinct比较对象
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John", Age = 18 } , new Student() { StudentID = 2, StudentName = "Steve", Age = 15 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } , new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 } }; var distinctStudents = studentList.Distinct(new StudentComparer()); foreach(Student std in distinctStudents) Console.WriteLine(std.StudentName);
John Steve Bill Ron
C# 查询语法不支持 Distinct 运算符。但是,您可以使用 Distinct 方法查询变量或将整个查询包装到括号中,然后调用 Distinct ()。
在VB.Net查询语法中使用Distinct关键字:
Dim strList = New List(Of string) From {"One", "Three", "Two", "Two", "One" } Dim distinctStr = From s In strList _ Select s Distinct