开发者

Linq query on Dictionary<int, double> type

开发者 https://www.devze.com 2023-01-18 01:18 出处:网络
I have a dictionary of type Dictionary<int, double> and want to eliminate values equal to a certain value.

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>>

0

精彩评论

暂无评论...
验证码 换一张
取 消