简体   繁体   中英

C# Determining value in dictionary

I've got a dictionary first<string, double> with double values range between 0 to 1, I want to make another dictionary that takes only 10 values, but those which are the furthest from 0.5. Firstly I was thinking about making dictionaries asc/desc, but what if the values were like 10 x 0.9 in desc, and around 0.45. in asc order, then I would only want to get higher values since 0.45 is only 0.05 from 0.5 and 0.9 is 0.4 away from the center.

Is there any way in dictionary to do this, or I need to code in loop like:

abs(first.Value - 0.5) and then add this value with the same key into new dictionary and use .Take(10) ?

var second = first.OrderByDescending(kvp => Math.Abs(kvp.Value - 0.5))
                  .Take(10)
                  .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Dictionary<string, double> firstDic = new Dictionary<string, double>();
// fill

Dictionary<string, double> secondDic = (from e in firstDic
                                        let distance = Math.Abs(e.Value - 0.5)
                                        orderby distance descending
                                        select e).Take(10).ToDictionary(e => e.Key, e => e.Value);

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