- Home /
Getting the sum of random values in the dictionary
Hello all!
Coding C# question here!
I have inventory with 4 different objects: Lemon, Apple, Coffee, Mango
each object has different score: 20, 40, 60, 80 (respectively).
I want to use dictionary to assign the values. Dictionary<string, float> scoreDictionary = new Dictionary<string, float>()
Now whenever I see only apple, Lemon and Mango (or other combination), I want the method to sum their values
So my plane is to add each value to dictionary and then be able to sum the values based on the Key I get.
if ((rows[0].stoppedSlot != rows[1].stoppedSlot) && (rows[1].stoppedSlot != rows[2].stoppedSlot)) { for (int i = 0; i < prizeDictionary.Count; i++) { // here summarize the three values I get } }
So basically, in other script I assign a string and add it's name + value to a dictionary,
and in the other script I want to say, "take the strings that you get" and sum the values based on the string name.
I really think you want a list.
public class thing {
public string fruit;
public int cost;
public thing (string f,int c){
fruit = f;cost = c;
}}
List<thing> basket;
void Start(){
basket = new List<thing>();
basket.Add (new thing("bannana", 50));
basket.Add (new thing("taco", 13));
basket.Add (new thing("green beans", 34));
basket.Add (new thing("bannana", 63));
int sum = 0;
for (int i = 0; i < basket.Count; i++) {
if(basket[i].fruit=="bannana"){
sum+=basket[i].cost;
}}
print ("total:" + sum);
}
Answer by tehpro_unity · Dec 31, 2018 at 01:22 AM
float sum = prizeDictionary["Apple"] + prizeDictionary["Lemon"] + prizeDictionary["Mango"];
Hope I understood you correctly what you want to do.
Answer by Tobychappell · Dec 31, 2018 at 01:22 PM
Use Linq.
class DemoClass
{
private Dictionary<string, float> prizeDictionary = new Dictionary<string, float>() {
{ "lemon", 20},
{ "apple", 40},
{ "coffee", 60},
{ "mango", 80},
};
public float GetSum(params string[] nKeys)
{
return prizeDictionary.Where(x => nKeys.Contains(x.Key)).Sum(y => y.Value);
}
public float GetSumWithDuplicates(params string[] nKeys)
{
return nKeys.Select(x => prizeDictionary.ContainsKey(x) ? prizeDictionary[x] : 0).Sum();
}
}
Test Project:
class Program
{
static void Main(string[] args)
{
DemoClass demo = new DemoClass();
Console.WriteLine("Score 1: " + demo.GetSum("apple", "coffee"));
List<string> keys = new List<string>
{
"lemon",
"mango",
"mango",
"mango",
"not a key",
"car"
};
Console.WriteLine("Score 2: " + demo.GetSumWithDuplicates(keys.ToArray()));
Console.ReadLine();
}
}
Output:
Score 1: 100
Score 2: 260