Study/C#, Winform

[C#] Enumerable 에서 중복 데이터 삭제 (Distinct)

2022. 10. 6. 19:40
목차
  1. Custom Class의 Distinct 사용
  2. 참고 자료

C#에서 Enumerable 형식의 데이터에서 중복을 없앨 때는 Distinct를 사용합니다.

 

public static System.Collections.Generic.IEnumerable<TSource> Distinct<TSource> (this System.Collections.Generic.IEnumerable<TSource> source);

원형은 위와 같습니다.

 

이것을 사용해보겠습니다.

List<int> list = new List<int> { 1, 2, 3, 4, 4, 4, 5, 6 };
list.Distinct().ToList().ForEach(num =>
{
    System.Console.Write($"{num} ");
});
System.Console.WriteLine();

double[] dArr = new double[] { 1.2, 3.3, 3.3, 3.3, 4.8, 4.8, 6.5 };
dArr.Distinct().ToList().ForEach(num =>
{
    System.Console.Write($"{num} ");
});
System.Console.WriteLine();

(간단하게 출력을 위해 List로 변환 후 ForEach를 사용하였습니다.)

이렇게 중복이 잘 제거된 것을 볼 수 있습니다.

 

Custom Class의 Distinct 사용

위에 있던 int, double, string 과 같은 Primitive 자료형이 아닌 직접 선언한 클래스를 사용할 때 Distinct를 사용하기 위해서는 IEquatable 인터페이스를 정의해주어야 합니다.

 

public class Human : IEquatable<Human>		// <-- IEquatable<클래스명> 상속
{
    public string Name { get; set; } = string.Empty;
    public int Age { get; set; } = 0;

	// Equals 정의
    public bool Equals(Human other)
    {
        return true;
    }
	
    // GetHashCode Override
    public override int GetHashCode()
    {
        return base.GetHashCode();
    }
};

 

Equals 와 GetHashCode 함수를 정의해주겠습니다.

public class Human : IEquatable<Human>
{
    public string Name { get; set; } = string.Empty;
    public int Age { get; set; } = 0;

    public bool Equals(Human other)
    {
        if (ReferenceEquals(other, null)) 
            return false;

        if (ReferenceEquals(this, other)) 
            return true;

        return Age == other.Age && Name.Equals(other.Name);
    }

    public override int GetHashCode()
    {
        int hashProductName = Name == null ? 0 : Name.GetHashCode();
        int hashProductCode = Age.GetHashCode();

        return hashProductName ^ hashProductCode;
    }
};

 

 

이제 이 Class를 가지고 Distinct를 수행해보겠습니다.

 

List<Human> list = new List<Human>
{ 
    new Human { Name = "Hong", Age = 30 },
    new Human { Name = "Hong", Age = 30 },
    new Human { Name = "Kim", Age = 30 },
    new Human { Name = "Jeon", Age = 55 },
    new Human { Name = "Koo", Age = 55 }
};
list.Distinct().ToList().ForEach(human =>
{
    System.Console.WriteLine($"{human.Name} : {human.Age}");
});

 

참고 자료

 

Enumerable.Distinct 메서드 (System.Linq)

시퀀스의 고유 요소를 반환합니다.

learn.microsoft.com

 

저작자표시 비영리 변경금지 (새창열림)

'Study > C#, Winform' 카테고리의 다른 글

[C# Winform] DataGridView Column Header Drag (컬럼 헤더 드래그)  (0) 2022.10.24
[C#] DateTime 시간 자르기, 반올림, 반내림, 가까운 값  (1) 2022.10.11
[C# Winform] 스크롤바 크기 (넓이)  (0) 2022.10.04
[C# Winform] Context Menu를 Button 옆에 띄우기  (0) 2022.09.28
[C#] MemoryStream, StreamWriter, StreamReader, BinaryWriter, BinaryReader  (1) 2022.08.16
  • Custom Class의 Distinct 사용
  • 참고 자료
'Study/C#, Winform' 카테고리의 다른 글
  • [C# Winform] DataGridView Column Header Drag (컬럼 헤더 드래그)
  • [C#] DateTime 시간 자르기, 반올림, 반내림, 가까운 값
  • [C# Winform] 스크롤바 크기 (넓이)
  • [C# Winform] Context Menu를 Button 옆에 띄우기
Eskeptor
Eskeptor
Eskeptor
Hello World
Eskeptor
전체
오늘
어제
  • 분류 전체보기 (138)
    • Computer (5)
      • Linux (1)
      • Hardware (2)
      • Software (0)
      • Tips (1)
      • Website (0)
    • Mobile (1)
      • Application (1)
    • Study (108)
      • Android (9)
      • C언어 (45)
      • C++ (17)
      • Unity 5(유니티5) (11)
      • Qt 프로그래밍 (2)
      • MFC (12)
      • C#, Winform (12)
    • My World (24)
      • OpenPad(Android) (12)
      • 한글 패치 (1)
      • C#으로 만든 귀요미들 (5)
      • MFC로 만든 귀요미들 (6)
    • Life Goes On (0)
      • Hip Hop (0)

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • 왕초보
  • 기초
  • 메모장
  • 슈팅게임
  • 초보
  • 오픈패드
  • 만들기
  • 비행기
  • 강의
  • 기본
  • 배열
  • 프로그래밍
  • Java
  • MFC
  • openpad
  • 안드로이드
  • 알고리즘
  • C언어
  • 유니티
  • Android
  • C#
  • 강좌
  • C++
  • 테트리스
  • 포인터
  • 자바
  • c++11
  • Tetris
  • Unity
  • 자료구조

최근 댓글

최근 글

hELLO · Designed By 정상우.
Eskeptor
[C#] Enumerable 에서 중복 데이터 삭제 (Distinct)
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.