Search code examples
c#.netlinqdictionary

How to sort a dictionary by key


I have dictionary Dictionary<string, Point>

the Key is c1,c3,c2,t1,,t4,t2 I want to sort them to be c1,c2,c3,t1,t2,t3

I'm trying to sort it using

Input.OrderBy(key => key.Key );

but it doesn't work

any idea how to solve that


Solution

  • ok check this it should work

    var r = new Dictionary<string, Point>();
    r.Add("c3", new Point(0, 0));
    r.Add("c1", new Point(0, 0));
    r.Add("t3", new Point(0, 0));
    r.Add("c4", new Point(0, 0));
    r.Add("c2", new Point(0, 0));
    r.Add("t1", new Point(0, 0));
    r.Add("t2", new Point(0, 0));
    var l = r.OrderBy(key => key.Key);
    var dic = l.ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value);
    
    foreach (var item in dic)
    {
    
        Console.WriteLine(item.Key);
    }
    Console.ReadLine();