c# - 比较字典中值之间的差异

标签 c# linq dictionary

我有一个 Dictionary<string, float> 并想从中选择 KeyValuePairs,其中浮点值之间的差异小于某个阈值。

这是字典:

Dictionary<string, float> heights = new Dictionary<string, float> ();

示例条目:

"first", 61.456
"second", 80.567
"third", 62.456
"4", 59.988
"5", 90.34
"6", 82.123

我需要这些元素,它们的值差异很小,例如列表中的“第一”、“第三”和“4”或类似的东西。区别是给定的浮点值,比方说 3.5

是否可以通过 Linq 实现?

我试着用循环来做到这一点,但不知何故它变得非常困惑......

最佳答案

您可以创建查找接近值并接受两个参数的自定义方法:保存值的字典和用于保存最大查找范围的 float :

    static Dictionary<string, float> FindRange(Dictionary<string, float> dict, float precision)
    {
        Dictionary<string, float> temp = new Dictionary<string, float>();
        List<int> counter = new int[dict.Count].ToList(); float[] values = dict.Values.ToArray();            

        for (int i = 0; i < values.Length; i++)                            
            for (int i2 = 0; i2 < values.Length; i2++)
                if (i2 != i && Math.Abs(values[i] - values[i2]) < precision) counter[i]++;            

        for (int i = 0; i < values.Length; i++)    
           if (Math.Abs(values[i] - values[counter.IndexOf(counter.Max())]) < precision) 
               temp.Add(dict.FirstOrDefault(kv => kv.Value == values[i]).Key, values[i]);

        return temp;
    }

使用示例:

static void Main()
{
        Dictionary<string, float> heights = new Dictionary<string, float>()
        {

            {"first", 61.456f},
            {"second", 80.567f},
            {"third", 62.456f},
            {"4", 59.988f},
            {"5", 90.34f},
            {"6", 82.123f}                
        };

        // returns max sequence of elements with difference less than 3f
        var newDict = FindRange(heights, 3f);

        foreach (var item in newDict)
        {
            Console.WriteLine(item.Key + "   "  + item.Value);
        }
}

输出:

first 61,456
third 62,456
4     59,988

关于c# - 比较字典中值之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32006487/

相关文章:

c# - C# DLL 库中的 String.ToLower

python - 从字符串中提取 Python 字典

c# - Windows 8 应用程序 - MediaElement 不播放 ".wmv"文件

c# - 如何使用 Linq 返回列值已更改的列表或可枚举行

c# - C# 中的双向 KeyValuePair 集合

c# - 使用 LINQ 进行标记枚举合并(组合的逆)

python - 在Python中同时迭代2个不同的字典

C++ 在键上将两个映射相交,保留第一个映射的值

c# - 在 C# 中将 char 转换为 int

c# - "End of Message"套接字字符串