본문 바로가기
2/[ C# ]

[C#] Dictionary Value 內 List 중복 제거

by Kieran_Han 2022. 5. 28.

내가 다루고 있는 Dictionary 형태는 Dictionary<string, List<Double>>이며, 주로 구현하고자하는 기능은 새로운 Value <List<Double>>이 추가되었을 때, 기존에 갖고 있는 List<Double>을 제외하고 새로운 List만 가져오는 것이다.

StackOverflow 구글링하다가 2가지 방법을 알았다.

 

1. List를 새로 생성하여 새로운 List를 만들어서 Dict 내 Key를 새로운 List로 바꾸기

// 할당된 경로 내 동일한 Dict Value List가 있는 경우 삭제 후 새로운 File Path Dict 생성

List<string> dict_file_0_list = new List<string>();

for (int i = 0; i < dict_file_0["Batch1"].Count; i++)
{
    dict_file_0_list.Add(dict_file_0["Batch1"][i]);
}

List<string> dict_file_list = new List<string>();

for (int i = 0; i < dict_file["Batch1"].Count; i++)
{
    dict_file_list.Add(dict_file["Batch1"][i]);
}

// List 2개를 1개로 합치기
dict_file_0_list.ForEach(x => dict_file_list.Add(x));

// List 내 중복 내용 지운 새로운 파일 List
List<string> dict_file_list_new = dict_file_list.GroupBy(x => x).Where(x => x.Count() == 1).Select(x => x.Key).ToList();

dict_file["Batch1"] = dict_file_list_new;

 

2. TryGetValue 방법

List<string> value_old;
dict_file_0.TryGetValue("Batch1", out value_old);

List<string> value_new;
dict_file.TryGetValue("Batch1", out value_new);

value_old.ForEach(x => value_new.Add(x));
List<string> value_no_duplicate = value_new.GroupBy(x => x).Where(x => x.Count() == 1).Select(x => x.Key).ToList();

dict_file["Batch1"] = value_no_duplicate;

 

위 2가지 방법 중 두번째 방법이 코드가 짧기 때문에, 우선은 2번재 방법으로 구현하고자 한다.

하지만, 어차피 함수로 만들어서 Batch 1~9까지 넣어야하기 때문에 크게 문제는 없을 것 같기도하지만.. 혹시 모를 나중에 Debuging을 위해 두번째 방법을 이용한다. (2022.05.28)