LINQ Set運算符 Distinct

下表列出了LINQ中可用的所有Set運算符。

集合運算符用法
Distinct

返回集合中的非重復值。

Except

返回兩個序列之間的差,這意味著一個集合中的元素不出現(xiàn)在第二個集合中。

Intersect

返回兩個序列的交集,即同時出現(xiàn)在兩個集合中的元素。

Union

返回兩個序列中的唯一元素,這意味著出現(xiàn)在兩個序列中的唯一元素。

Distinct

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擴展方法不比較復雜類型對象的值。為了比較復雜類型的值,需要實現(xiàn)IEqualityComparer<T>接口。在下面的示例中,StudentComparer類實現(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

查詢語法中的Distinct運算符

C# 查詢語法不支持 Distinct 運算符。但是,您可以使用 Distinct 方法查詢變量或?qū)⒄麄€查詢包裝到括號中,然后調(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
丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清