繁体   English   中英

我如何计算字典 c# 中相等值的数量

[英]how do I count the number of equal values in a dictionary c#

我想要做的是将内置在字典中的测试数据集与也内置在字典中的学习数据集进行比较。 我尝试了多种方法,我要么在所有检查中得到 0,要么得到不可能的答案(我认为它对测试集的所有整数都计数),而不是它看起来应该做的事情,这(所以我一直在想)在训练集中的每个键/值对之后重置计数。

这是执行此操作的代码示例。 帮助?

 public static void theTestingAlgorithm()
    {
        foreach (var testrecipe in Testing.sortedTestingData)
        {
            Dictionary<string, int> runningNumbers = new Dictionary<string, int>();
            foreach(var learningRecipe in MakeData.SortedData)
            {
                runningNumbers.Add(learningRecipe.Key, 0);
            }                
            foreach(var testIngredient in testrecipe.Value)
            {
                foreach(var learningRecipe in MakeData.SortedData)
                {
                    if (learningRecipe.Value.Contains<string>(testIngredient))
                    {
                        runningNumbers[learningRecipe.Key]++;
                    }
                }
            }       
            string answer = evaluatetest(runningNumbers);
            runningNumbers.Clear();
            Answers.Add(testrecipe.Key, answer);
        }
    }

看起来您正在尝试计算一种成分在所有测试食谱中出现的次数。 我认为您不想在 foreach 中创建runningNumbers

这是一个 linq 表达式,可以让您更接近您正在寻找的内容......

        Dictionary<string, string[]> SortedTestingData = new Dictionary<string, string[]>();
        SortedTestingData.Add("1", new string[] { "a", "b", "c" });
        SortedTestingData.Add("2", new string[] { "d", "b", "e" });
        SortedTestingData.Add("3", new string[] { "d", "b", "f" });
        SortedTestingData.Add("4", new string[] { "a", "b", "c" });

        var runningNumbers = from vals in SortedTestingData
                             from val in vals.Value
                             group val by val into g
                             select new
                             {
                                 Value = g.Key,
                                 Count = g.Count()
                             };

这是值中每个字符串每次出现次数的列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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