히가츠류의 보금자리

[Programming] C# Dictionary 다양한 정렬 방법 (오름/내림차순, orderBy, Sorting) 본문

Programming

[Programming] C# Dictionary 다양한 정렬 방법 (오름/내림차순, orderBy, Sorting)

HiGaTsu Ryu 2022. 10. 28. 16:29

Dictionary 정렬 시에 항상 OrderBy() 등을 사용하거나, List로 변환하여 사용했었는데

신기한 코드를 발견하여 정리 겸 메모해둔다.

 

[Sort the keys and values in a Dictionary with orderby and query expressions.]

쿼리문을 사용하는 것으로 보인다.

	Dictionary<int, string> testDictionary = new Dictionary<int, string>();				// Dictionary 선언
	var items = from pair in testDictionary orderby pair.Key ascending select pair;		// Sorting

	foreach (KeyValuePair<int, string> pair in items)
	{
		// To do..
		Debug.Log("{0}: {1}", pair.Key, pair.Value);
	}

 

 

 - 핵심 코드 : "var items = from pair in testDictionary orderby pair.Key ascending select pair;"

 

 

편의를 위해 var을 사용하였는데, 여기서 items는 IOrderedEnumerable<KeyValuePair<Key 타입, Value 타입>> 이다.

해당 타입은 System.Linq; 에 포함되어있으니 using 꼭 확인할 것.

 

오름/내림차순 설정은 해당 코드의 'ascending' 부분을 수정하면 된다. 

- ascending : 오름차순 (1, 6, 9, ...)
- descending : 내림차순 (99, 88, 50, ...)

 

Key값 기준 정렬이 아닌 Value 기준 정렬이 필요할 경우 'pair.key' 부분을 'pair.value'로 변경할 것.

 

 

 

+) 추가로.. 아직 성능상으로 어느 것이 더 좋은지, 이 외 문제점이 있는지는 확인하지 못했다.

    왜 많은 사람들이 OrderBy를 주로 사용하는지도 이유를 모른다. 관련해서 아시는 분은 댓글 부탁드립니다.

 

 

[OrderBy, OrderByDescending]

            var valueAscendingResult = testDictionary.OrderBy(x => x.Value);
            var keyDescendingResult = testDictionary.OrderByDescending(x => x.Key);

그냥 OrderBy가 직관적이라 사용하는 걸지도...

 

 

 

[참고 자료]

: https://www.dotnetperls.com/sort-dictionary

 

C# Sort Dictionary: Keys and Values - Dot Net Perls

Sorting approaches. We can sort a Dictionary with the Keys and Values properties and a List instance. Some approaches are slower than others. Notes, other methods. Other methods I found involve more steps, code or complexity. There is nothing wrong with th

www.dotnetperls.com

 

 

잘못된 사항 혹은 수정이 필요한 부분은 댓글 부탁드립니다!!

더 좋은 의견도 항상 환영합니다!

Comments