반응형
반응형

다음과 같은 배열이 있다.

int[] arr = { 1, 5, 2, 2, 2, 2, 5, 5, 4, 6, 8, 1, 2 };

 

1은 2개, 2는 5개, 5는 3개가 중복돼 있다.

 

여기서 중복 요소를 코드로 구하는 법은?


 

(Linq) 배열에서 중복 요소와 개수를 구하는 법

 

 

1. 중복이 있는 요소들과 그중 제일 큰 수
int[] arr = { 1, 5, 2, 2, 2, 2, 5, 5, 4, 6, 8, 1, 2 };

 var 중복이_있는_요소 = arr
     .GroupBy(x => x)
     .Where(x => x.Count() > 1)
     .Select(x => x.Key);
     
 Console.WriteLine(string.Join(", ", 중복이_있는_요소));
 Console.WriteLine(중복이_있는_요소.Max());
 
 
 
#결과
1, 5, 2
5

 

 

 

2. 제일 많이 중복돼 있는 수
int[] arr = { 1, 5, 2, 2, 2, 2, 5, 5, 4, 6, 8, 1, 2 };

var 중복이_제일_많은_수 = arr
    .GroupBy(x => x)
    .OrderByDescending(x => x.Count())
    .Where(x => x.Count() > 1)
    .Select(x => x.Key).First();
        
Console.WriteLine(중복이_제일_많은_수);



#결과
2

 

 

 

3. 중복된 요소들의 개수
int[] arr = { 1, 5, 2, 2, 2, 2, 5, 5, 4, 6, 8, 1, 2 };

Console.WriteLine(arr.Count() - arr.Distinct().Count());



#결과
7

 

 

 

4. 중복 요소 딕셔너리(요소, 중복 개수)
int[] arr = { 1, 5, 2, 2, 2, 2, 5, 5, 4, 6, 8, 1, 2 };

var 중복_딕셔너리 = arr
    .GroupBy(x => x)
    .Where(x => x.Count() > 1)
    .ToDictionary(x => x.Key, y => y.Count());

Console.WriteLine("중복 딕셔너리 : " + string.Join(" ", 중복_딕셔너리));



#결과
중복 딕셔너리 : [1, 2] [5, 3] [2, 5]

 

 

 

5. 중복 요소 딕셔너리 Key순으로 정렬(오름차순)
int[] arr = { 1, 5, 2, 2, 2, 2, 5, 5, 4, 6, 8, 1, 2 };

var 중복_딕셔너리_key정렬 = arr
    .GroupBy(x => x)
    .OrderBy(x => x.Key)
    .Where(x => x.Count() > 1)
    .ToDictionary(x => x.Key, x => x.Count());

Console.WriteLine("중복 딕셔너리 Key정렬(오름차순) : " + string.Join(" ", 중복_딕셔너리_key정렬));



#결과
중복 딕셔너리 Key정렬(오름차순) : [1, 2] [2, 5] [5, 3]

 

 

 

6. 중복 요소 딕셔너리 Value순으로 정렬(내림차순)
int[] arr = { 1, 5, 2, 2, 2, 2, 5, 5, 4, 6, 8, 1, 2 };

var 중복_딕셔너리_value정렬 = arr
    .GroupBy(x => x)
    .OrderByDescending(x => x.Count())
    .Where(x => x.Count() > 1)
    .ToDictionary(x => x.Key, x => x.Count());

Console.WriteLine("중복 딕셔너리 Value정렬(내림차순) : " + string.Join(" ", 중복_딕셔너리_value정렬));



#결과
중복 딕셔너리 Value정렬(내림차순) : [2, 5] [5, 3] [1, 2]

Linq 쓰는 거 너무 편해~

반응형

+ Recent posts