简体   繁体   中英

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

What I am trying to do, is compare a test data set, built into a dictionary, to the learning data set, which is also built into a dictionary. I have tried a number of ways, and I either get 0's back on all the checks, or I get answers that are impossible (I think that it's counting for all int the testing set) rather than what it looks like it should be doing, which (SO I keep thinking) resetting the counts after each key/value pair in the training set.

Here's an example of code that's doing that. help?

 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);
        }
    }

It looks like you are trying to figure out how many times an ingredient appears in all of your test recipes. I don't think you want to create your runningNumbers inside the foreach.

Here is a linq expression that may get you closer to what you are looking for...

        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()
                             };

This is a list of the count of each occurrence of each string in the values.

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