+ 1

Can we perform mathematical operations for dictionary values type integer in c#, and how?

Like This Code Dictionary<string, int> dictionary =new Dictionary<string, int>(); //add keys and values in the dictionary dictionary.Add("YEM", 124); dictionary.Add("SHA", 20); dictionary.Add("MOH", 63); dictionary.Add("SAL", 84); I need to find the Percentage for each value how I can do that

17th Nov 2021, 7:33 PM
Shafiq Almatari
Shafiq Almatari - avatar
4 Respuestas
+ 7
Shafiq Mohammed Almatri , in python it can be done like: dic = {"YEM": 124, "SHA": 20, "MOH": 63, "SAL": 84} total = sum(dic.values()) the variable total holds now the sum of all values. in the next step use a for loop, pick each value from dic and calculate the percentage by using the total
17th Nov 2021, 7:49 PM
Lothar
Lothar - avatar
+ 3
Shafiq Mohammed Almatri , we have presented you 2 code snippets that can do the requested task. the rest is basic mathematical stuff. if you need more, please do a try and post it here if you get stuck somewhere.
18th Nov 2021, 9:56 AM
Lothar
Lothar - avatar
+ 2
You can perform mathematical operations on numbers. In this case the dictionary values are int, so yes, you can. To calculate the sum of all values you can do this: int sum = dictionary.Values.Sum(); Then you can loop over the dictionary and calculate the percentage by dividing each value by the sum.
17th Nov 2021, 7:46 PM
Tibor Santa
Tibor Santa - avatar
+ 1
Well... If we want to calculate the tax for each value Like This If YEM =124 , tax=5% Then The tax will be 124*5/100 =6.2 How I can return the value of YEM after take the tax YEM with new value=124-6.2=117.8
17th Nov 2021, 10:25 PM
Shafiq Almatari
Shafiq Almatari - avatar