C# sort dictionary with linq

前端 未结 4 916
夕颜
夕颜 2021-01-02 00:43

I have a dictionary in C#:

public Dictionary

And I would like to get my result in to a generic list:

Li         


        
相关标签:
4条回答
  • 2021-01-02 00:55
    MyDict.OrderByDescending(x => x.Value).Select(p => p.Key).ToList();
    
    0 讨论(0)
  • 2021-01-02 00:57

    You can do that using:

    List<Product> productList = dictionary.OrderByDescending(kp => kp.Value)
                                          .Select(kp => kp.Key)
                                          .ToList();
    
    0 讨论(0)
  • 2021-01-02 01:05

    Try this

    List<Product> productList = dictionary.OrderByDescending(x => x.Value).Select(x => x.Key).ToList();
    
    0 讨论(0)
  • 2021-01-02 01:22

    Here's an example using LINQ query syntax.

     public class TestDictionary 
        {
            public void Test()
            {
                Dictionary<Product, int> dict=new Dictionary<Product, int>();
                dict.Add(new Product(){Data = 1}, 1);
                dict.Add(new Product() { Data = 2 }, 2);
                dict.Add(new Product() { Data = 3 }, 3);
                dict.Add(new Product() { Data = 4 }, 9);
                dict.Add(new Product() { Data = 5 }, 5);
                dict.Add(new Product() { Data = 6 }, 6);
    
                var query=(from c in dict 
                    orderby c.Value descending 
                    select c.Key).ToList();       
            }
            [DebuggerDisplay("{Data}")]
            public class Product
            {
                public int Data { get; set; }
            }           
        }
    
    0 讨论(0)
提交回复
热议问题