Brad
Brad

Reputation: 163232

Cast troubles while using LINQ to filter a Dictionary by values

I've got a Dictionary<string,int> with a few values in it. For example:

I want to filter this list to keep values that are greater than 500. I don't use C# very often, and haven't used any LINQ. I thought that this might be a good time to learn. So, I have tried the following:

Dictionary<string,int> someDictionary = new Dictionary();

// Code to populate someDictionary goes here

someDictionary = (Dictionary<string,int>) someDictionary.Where(pair => pair.Value > 500);

This throws an InvalidCastException:

Unable to cast object of type 'WhereEnumerableIterator`1[System.Collections.Generic.KeyValuePair`2[System.String,System.Int32]]' to type 'System.Collections.Generic.Dictionary`2[System.String,System.Int32]'.

I've tried a handful of casts, calls to .ToDictionary(), etc. I cannot seem to figure out how to cast this correctly, or get the syntax quite right. Can you point me in the right direction? Thank you for your time.

Upvotes: 3

Views: 2206

Answers (1)

Bryan Hong
Bryan Hong

Reputation: 1483

You need to use ToDictionary, then pass the selector for the key, then the selector for the value.

someDictionary = someDictionary.Where(pair => pair.Value > 500)
                               .ToDictionary(p => p.Key, p => p.Value);

Upvotes: 12

Related Questions