Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I alter the contents of IDictionary using LINQ (C# 3.0)

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?
like image 338
Jader Dias Avatar asked Jun 04 '09 20:06

Jader Dias


3 Answers

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.

like image 165
Ryan Versaw Avatar answered Oct 17 '22 21:10

Ryan Versaw


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;
}
like image 4
Marc Gravell Avatar answered Oct 17 '22 19:10

Marc Gravell


foreach (var item in dictionary.Keys)
    dictionary[item] = 1;

I wonder why you might a need doing such a thing, though.

like image 2
mmx Avatar answered Oct 17 '22 20:10

mmx