How do I alter the contents of an IDictionary using C# 3.0 (Linq, Linq extensions) ?
var enumerable = new int [] { 1, 2};
var dictionary = enumerable.ToDictionary(a=>a,a=>0);
//some code
//now I want to change all values to 1 without recreating the dictionary
//how it is done?
This is not nearly as clear as other ways, but it should work fine:
dictionary.Keys.ToList().ForEach(i => dictionary[i] = 0);
My other alternative would have been to make a ForEach extension method similar to this:
public static class MyExtensions
{
public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
{
action(item);
}
}
}
Then use it like this:
dictionary.ForEach(kvp => kvp.Value = 0);
This won't work in this case though, as Value cannot be assigned to.
LINQ is a query dialect - it isn't directly a mutation language.
To change the values of an existing dictionary, foreach
is probably your friend:
foreach(int key in dictionary.Keys) {
dictionary[key] = 1;
}
foreach (var item in dictionary.Keys)
dictionary[item] = 1;
I wonder why you might a need doing such a thing, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With