I have a Dictionary of objects defined like this -
Dictionary<string, MyObject> myObjectDictionary
I would like to grab items in the Dictionary based of an index and count of items. I am trying to use Skip
and Take
. But this requires recasting it back to Dictionary<string, MyObject>
. How can this be done? Is there a different way I should be doing this?
Here is my code and failed attempt to recast -
Dictionary<string, MyObject> myObjectDictionary = FillMyObjectDictionary();
var mySmallerObjectDictionary = myObjectDictionary.Skip(startNumber).Take(count);
//THE FOLLOWING DOES NOT WORK
Dictionary<string, MyObject> myNewObjectDictionary = (Dictionary<string, MyObject>)mySmallerObjectDictionary
Well, you can create a new dictionary:
Dictionary<string, MyObject> myNewObjectDictionary =
myObjectDictionary.Skip(startNumber)
.Take(count)
.ToDictionary(pair => pair.Key, pair => pair.Value);
However:
You shouldn't rely on the ordering of a dictionary. It's not clear which items you wish to skip. Consider using OrderBy
before Skip
. For example:
Dictionary<string, MyObject> myNewObjectDictionary =
myObjectDictionary.OrderBy(pair => pair.Key)
.Skip(startNumber)
.Take(count)
.ToDictionary(pair => pair.Key, pair => pair.Value);
This does not preserve any custom equality comparer that was in the original dictionary. Unfortunately that's not exposed anywhere, so you'll just have to know whether or not FillMyObjectDictionary
uses a custom comparer.
See more on this question at Stackoverflow