当前位置:编程学习 > C#/ASP.NET >>

Dictionary 查找相近的两个值。

我用Dictionary存了一张表,key 为温度t(0—200),value为值,现在我有一个值,需要在这张表中找与之最相近的两个value,然后取出value和对应的t。怎么实现相近值的查找啊? --------------------编程问答-------------------- from entry in myDict orderby entry.Value ascending select entry
http://stackoverflow.com/questions/289/how-do-you-sort-a-dictionary-by-value --------------------编程问答--------------------
引用 1 楼 emailtome 的回复:
from entry in myDict orderby entry.Value ascending select entry
http://stackoverflow.com/questions/289/how-do-you-sort-a-dictionary-by-value


打不开啊。 --------------------编程问答-------------------- 200个的级别倒是可以逐个比较:

Dictionary<string, int> dict = new Dictionary<string, int>()
{
    {"one", 1},
    {"two", 2},
    {"nine", 9},
    {"five", 5},
};

int toCompare = 8;
var pair = dict.Aggregate(dict.First(), (next, result) => Math.Abs(next.Value - toCompare) < Math.Abs(result.Value - toCompare) ? next : result);
string key = pair.Key; // "nine";
--------------------编程问答--------------------
引用 2 楼 xuehan1108 的回复:
Quote: 引用 1 楼 emailtome 的回复:

from entry in myDict orderby entry.Value ascending select entry
http://stackoverflow.com/questions/289/how-do-you-sort-a-dictionary-by-value


我不需要排序,我的表现在是按升序排列的。我只需要找到相近的两个值。 --------------------编程问答-------------------- 既然你是升序排列的,比较第I个 和 第I+1个 的差值, 取差值最小的I 和I+1的键值对不就行了么 --------------------编程问答-------------------- 直接排序,然后遍历,找到符合条件的第i项以及第i+1项,条件如下

第i项 <= 你的给定值,第i+1项>= 你的给定值

另外注意一些边界的处理就好了 --------------------编程问答-------------------- ok了。谢谢。
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,