下表列出了LINQ中可用的所有Set運(yùn)算符。
| 集合運(yùn)算符 | 用法 |
|---|---|
| Distinct | 返回集合中的非重復(fù)值。 |
| Except | 返回兩個(gè)序列之間的差,這意味著一個(gè)集合中的元素不出現(xiàn)在第二個(gè)集合中。 |
| Intersect | 返回兩個(gè)序列的交集,即同時(shí)出現(xiàn)在兩個(gè)集合中的元素。 |
| Union | 返回兩個(gè)序列中的唯一元素,這意味著出現(xiàn)在兩個(gè)序列中的唯一元素。 |
Distinct擴(kuò)展方法從給定集合返回一個(gè)新的唯一元素集合。
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擴(kuò)展方法不比較復(fù)雜類型對象的值。為了比較復(fù)雜類型的值,需要實(shí)現(xiàn)IEqualityComparer<T>接口。在下面的示例中,StudentComparer類實(shí)現(xiàn)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();
}
}現(xiàn)在,您可以在Distinct()方法中傳遞上述StudentComparer類的對象作為參數(shù)來比較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 運(yùn)算符。但是,您可以使用 Distinct 方法查詢變量或?qū)⒄麄€(gè)查詢包裝到括號中,然后調(diào)用 Distinct ()。
在VB.Net查詢語法中使用Distinct關(guān)鍵字:
Dim strList = New List(Of string) From {"One", "Three", "Two", "Two", "One" }
Dim distinctStr = From s In strList _
Select s Distinct