Problems Using ToDictionary Extension Method
-
Hi, I have a dictionary of items. I want to create a new Dictionary by taking items from it where each item meets a particular criterion. I figure that the ToDictionary extension method would suit my purpose, but for the life of me I cannot get it to compile.
Dictionary test = new Dictionary{
{1 ,"a"},{2, "b"},{3 ,"c"},{4, "d"}
};Dictionary d = test.ToDictionary(o => o.Value.CompareTo("d") == -1);
// compiler error on this line
//'System.Collections.Generic.Dictionary' does not contain a definition for 'ToDictionary' and the best extension method overload //'System.Linq.Enumerable.ToDictionary(System.Collections.Generic.IEnumerable, System.Func)' has some //invalid argumentsThe only thing that I could manage that came close to what I need is:
List> t1 = test
.Where(o => o.Value.CompareTo("d") == -1)
.ToList>();I reckon I'm doing something really stupid but I can't see what it is. Can anyone help me out? Thanks very much, dlarkin77
-
Hi, I have a dictionary of items. I want to create a new Dictionary by taking items from it where each item meets a particular criterion. I figure that the ToDictionary extension method would suit my purpose, but for the life of me I cannot get it to compile.
Dictionary test = new Dictionary{
{1 ,"a"},{2, "b"},{3 ,"c"},{4, "d"}
};Dictionary d = test.ToDictionary(o => o.Value.CompareTo("d") == -1);
// compiler error on this line
//'System.Collections.Generic.Dictionary' does not contain a definition for 'ToDictionary' and the best extension method overload //'System.Linq.Enumerable.ToDictionary(System.Collections.Generic.IEnumerable, System.Func)' has some //invalid argumentsThe only thing that I could manage that came close to what I need is:
List> t1 = test
.Where(o => o.Value.CompareTo("d") == -1)
.ToList>();I reckon I'm doing something really stupid but I can't see what it is. Can anyone help me out? Thanks very much, dlarkin77
-
This will work for you:
IDictionary<int,string> d = (
from t in test
where t.Value.CompareTo("d") == -1
select t).
ToDictionary(item => item.Key, item => item.Value);regards