I am getting started with C# and got the following class:
using System;
using System.Collections.Generic;
class PrefixMapSum : Dictionary<String, int> {
public bool insert(String key, int value) {
return base.TryAdd(key, value);
}
public int sum(String prefix) {
int sum = 0;
foreach (String key in base.Keys) {
if (key.StartsWith(prefix)) {
sum = sum + base[key];
}
}
return sum;
}
}
Now I'd love to shorten the following part of the code with lambda-expressions:
foreach (String key in base.Keys) {
if (key.StartsWith(prefix)) {
sum = sum + base[key];
}
}
I tried with:
new List<String>(base.Keys).ForEach(key => key.StartsWith(prefix) ? sum = sum + base[key] : sum = sum);
Yet i am running into this error: CS0201
I am coming from Java and I can't quite figure out why it does not work. Can anyone explain what I should do differently (and why)?
ifblock. Assignments are expressions, so this call will return a value BUTForEachexpects statements that do something, not expressions