How to change IDictionary contents using LINQ (C # 3.0)

How to change the contents of 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?
+5
source share
3 answers

This is not as clear as other methods, but it should work fine:

dictionary.Keys.ToList().ForEach(i => dictionary[i] = 0);

My other alternative would be to make the ForEach extension method look like 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 as follows:

dictionary.ForEach(kvp => kvp.Value = 0);

This will not work in this case, since a value cannot be assigned.

+4
source

LINQ is a dialect of queries - it is not a mutation language.

To change the meaning of an existing dictionary foreach, probably your friend:

foreach(int key in dictionary.Keys) {
    dictionary[key] = 1;
}
+4
foreach (var item in dictionary.Keys)
    dictionary[item] = 1;

, , , , .

+2

All Articles