Johan
Johan

Reputation: 293

C# sort dictionary with linq

I have a dictionary in C#:

public Dictionary<Product, int>

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

List<Product> productList = new List<Product>();

With the products orderder descending by the int value in the dictionary. I've tried using the orderby method, but without success.

Upvotes: 18

Views: 34215

Answers (4)

crypted
crypted

Reputation: 10306

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; }
        }           
    }

Upvotes: 5

Stecya
Stecya

Reputation: 23266

Try this

List<Product> productList = dictionary.OrderByDescending(x => x.Value).Select(x => x.Key).ToList();

Upvotes: 6

Coding Flow
Coding Flow

Reputation: 21881

MyDict.OrderByDescending(x => x.Value).Select(p => p.Key).ToList();

Upvotes: 5

driis
driis

Reputation: 164291

You can do that using:

List<Product> productList = dictionary.OrderByDescending(kp => kp.Value)
                                      .Select(kp => kp.Key)
                                      .ToList();

Upvotes: 33

Related Questions