Unity/C#

c# Dictionary(딕셔너리) 관련

모카쨩 2024. 3. 19. 01:48

 

ClassList to Dictionary

아래의 경우에는 중복되는 userCode의 경우 price를 전부 병합하여 생성한다

왜냐면 Dictionary는 동일키생성을 허용하지 않기 때문이다

var dictionary = classList.GroupBy(x => x.userCode).ToDictionary(x=>x.First().userCode, x=>x.Sum(x=>x.price));

 

 

 

Dictionary Sort

//오름차순 정렬
dictionary=dictionary.OrderBy(x => x.Value).ToDictionary(x=>x.Key, x => x.Value); //오름차순 정렬
 
//내림차순 정렬
dictionary=dictionary.OrderByDescending(x => x.Value).ToDictionary(x=>x.Key, x => x.Value); //내림차순 정렬

 

 

슬라이스

{
    //슬라이스(길이만큼 자르기)
    var length = 3;
    dictionary = dictionary.Take(length).ToDictionary(x => x.Key, x => x.Value);
}

 

 

중복제거

단 Dictionary는 원래 중복 Key를 허용하지 않기 때문에 Value만 가능하다

dictionary = dictionary.GroupBy(x => x.Value).Select(x => x.First()).ToDictionary(x => x.Key, x => x.Value); //중복제거