简体   繁体   中英

Dictionary getting top most elements

Friends I have created a dictionary. For getting top 2 elements I am using below code.

topKeys[B] = (from entry in differentKeys orderby entry.Value descending 
             select entry)
                .ToDictionary(pair => pair.Key, pair => pair.Value).Take(2)
                .ToDictionary(x=>x.Key,x=>x.Value).Values.ToArray();

But it seems not working. Can you please suggest line in C# which will return me top 2 maximum elements? differentKeys is name of my dictionary. Check the snaps below...

在此处输入图片说明在此处输入图片说明

It's not clear why you keep converting to dictionaries all the time. The order of entries Dictionary<,> is not guaranteed.

It looks like you just want:

var topValues = differentKeys.Values
                             .OrderByDescending(x => x)
                             .Take(2)
                             .ToArray();

Or if you want the keys which correspond to the top values:

var keysForTopValues = differentKeys.OrderByDescending(x => x.Value)
                                    .Select(x => x.Key)
                                    .Take(2)
                                    .ToArray();

Not sure what your expected output and the actual output is, but you seem to be wanting to get top 2 from your dictionary.

Dictionary<string, string> sample = new Dictionary<string, string>();
sample.Add("First", "Yasser");
sample.Add("Second", "Amit");
sample.Add("Third", "Sachin");
sample.Add("Fourth", "Kunal");

Dictionary<string, string> top2 = sample.Take(2).ToDictionary(m => m.Key, m => m.Value);

Update : Just noticed your were using "descending" in your code.

Incase you want to sort on key use this

sample.OrderByDescending(m => m.Key).Take(2)

You should not keep converting to dictionaries all the time, also, what type is differentKeys really? I'm assuming here that it is some kind of IEnumerable<T> . If differentKeys is a IDictionary<K,V> , go with Jon's answers, ie use the Values property for the collection of values instead of selecting them via Linq.

topKeys[B] = (from entry in differentKeys orderby entry.Value descending 
              select entry.Value)
              .Take(2)
              .ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM