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
The Dictionary<TKey, TValue> Class in C# is a collection of Keys and Values. It is a generic collection class in the System. Collections. Generic namespace. The Dictionary <TKey, TValue> generic class provides a mapping from a set of keys to a set of values.
Dictionary is a collection of keys and values in C#. Dictionary is included in the System. Collection. Generics namespace.
foreach loop: You can use foreach loop to access the key/value pairs of the dictionary.As shown in the below example we access the Dictionary using a foreach loop.
It is a class hence it is a Reference Type.
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.
The result of the Skip
/ Take
operation will not be an IDictionary<string, MyObject>
, it will be an IEnumerable<KeyValuePair<string, MyObject>>
.
If you want to convert this back to a dictionary, try calling ToDictionary
:
var myNewObjectDictionary = mySmallerObjectDictionary.ToDictionary(p => p.Key, p => p.Value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With