Linq query on Dictionary<int, double> type
I have a dictionary of type Dictionary<int, double>
and want to eliminate values equal to a certain value.
At the moment I have
Dictionary <int, double> dict = GetDictionary();
dict = dict.Where(x => x.Value != 100).Select(x => x);
And am getting the error:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<int,double>>
' to 'Syste开发者_Python百科m.Collections.Generic.Dictionary<int,double>
'. An explicit conversion exists (are you missing a cast?)
How can I achieve what I'm trying to do using Linq?
Using LINQ:
var newDict = dict.Where(kvp => kvp.Value != 100)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
The reason you are getting a compile error is that Select is an extension on IEnumerable. In the case of a Dictionary<TKey,TValue>
you are dealing with an IEnumerable<KeyValuePair<TKey,TValue>>
精彩评论