English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

LINQ Set 연산자 Distinct

다음 표는 LINQ에서 사용할 수 있는 모든 Set 연산자를 나열합니다.

집합 연산자사용법
Distinct

집합에서 중복되지 않는 값을 반환합니다.

Except

두 시퀀스 간의 차집합을 반환합니다. 즉, 두 번째 집합에 없는 첫 번째 집합의 요소를 의미합니다.

Intersect

두 시퀀스의 교집합을 반환합니다. 즉, 두 집합에서 모두 나타나는 요소입니다.

Union

두 시퀀스에서의 유일한 요소를 반환합니다. 이는 두 시퀀스에서 모두 나타나는 유일한 요소를 의미합니다.

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 확장 메서드는 복잡한 타입 객체의 값을 비교하지 않습니다. 복잡한 타입의 값을 비교하려면 IEqualityComparer<T> 인터페이스를 구현해야 합니다. 아래 예제에서 StudentComparer 클래스는 IEqualityComparer<Student>를 구현하여 Student 객체를 비교합니다.

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

쿼리 문법에서 Distinct 연산자

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