Ken'ichi Matsuyama
Ken'ichi Matsuyama

Reputation: 369

Iterating through dictionary and doing some stuff

is it possible to iterat through dictionary like this?

  1. I want to count all dictionary items (sum every Value),
  2. Next, for each Key I want to take their Value
  3. Then, I want to divide every EACH Key Value with sum
  4. And lasty I want to multiply every output from 3

I made it so it works with 1 item, but not sure how to make it so it works with every item in dictionary.

Here is sample code for 1 item:

var dic = new Dictionary<string, int>();
//this is sum
double y = 0;
foreach (var item in dic)
{
     y += item.Value;
}
//this is selected item
double x = 0;
foreach (var item in dic)
{               
    if (item.Key == "Smith")
    {
        x = item.Value;
    }
}
double z = 0;
z = x / y;
Console.WriteLine("Smith/DicSum: " + z);

Now I would like to multiply the Z's (each Z's for each key in dictionary).

I was thiking about making one big loop for this like:

for (int i=0; i<y; i++) where y is the sum for all items in dictionary and multiply z's on the end of the loop

but I still don't know how to grab all seperate values and divide them while not saying the specific key for each of them.

@edit Thanks for answears but check my edit. I have a string list, let's say

"Smith is very cool member of Smith Company"

And my program is counting the number of Smith's, so it will show x as two. Then I want to divide snumber of smiths (two) by number of all words, so it's 2/8 = 0,25. Then I want to do this with every word and multiply it so it will be 2/8*1/8*...*1/8 in this example. SO I want to multiply by a preious number from loop (from dictionary), and not by a fixed amount, that's what making this problem.

Upvotes: 0

Views: 572

Answers (1)

Hamid Pourjam
Hamid Pourjam

Reputation: 20764

var words = "Smith is very cool member of Smith Company"
    .Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

var dic = new Dictionary<string, double>();

foreach (string word in words)
{
    if (dic.ContainsKey(word))
        dic[word]++;
    else
        dic[word] = 1;
}

var sum = dic.Sum(x => x.Value);
var result = dic.Values.Aggregate(1.0, (current, item) => current * (item / sum));

Upvotes: 2

Related Questions