티스토리 뷰

IT지식

c# dictionary sort 방법

민자르 2018. 4. 14. 11:26
반응형

1. dictionary key sort



using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // Create dictionary and add five keys and values.
        var dictionary = new Dictionary<string, int>();
        dictionary.Add("car", 2);
        dictionary.Add("apple", 1);
        dictionary.Add("zebra", 0);
        dictionary.Add("mouse", 5);
        dictionary.Add("year", 3);

        // Acquire keys and sort them.
        var list = dictionary.Keys.ToList();
        list.Sort();

        // Loop through keys.
        foreach (var key in list)
        {
            Console.WriteLine("{0}: {1}", key, dictionary[key]);
        }
    }
}

Output

apple: 1
car: 2
mouse: 5
year: 3
zebra: 0



2. dictionary value sort



using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // Example dictionary.
        var dictionary = new Dictionary<string, int>(5);
        dictionary.Add("cat", 1);
        dictionary.Add("dog", 0);
        dictionary.Add("mouse", 5);
        dictionary.Add("eel", 3);
        dictionary.Add("programmer", 2);

        // Order by values.
        // ... Use LINQ to specify sorting by value.
        var items = from pair in dictionary
                    orderby pair.Value ascending
                    select pair;

        // Display results.
        foreach (KeyValuePair<string, int> pair in items)
        {
            Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
        }

        // Reverse sort.
        // ... Can be looped over in the same way as above.
        items = from pair in dictionary
                orderby pair.Value descending
                select pair;
    }
}

Output

dog: 0
cat: 1
programmer: 2
eel: 3
mouse: 5



3. dictionary Order By



using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var items = new Dictionary<int, int>();
        items.Add(-1, 0);
        items.Add(0, 1);
        items.Add(-2, 0);
        items.Add(3, 1);

        // Use OrderBy method.
        foreach (var item in items.OrderBy(i => i.Key))
        {
            Console.WriteLine(item);
        }
    }
}

Output

[-2, 0]
[-1, 0]
[0, 1]
[3, 1]


728x90
반응형
댓글