开发者

C# Custom Dictionary Take - Convert Back From IEnumerable [duplicate]

This question already has answers here: Recreating a Dictionary from an IEnumerable<KeyValuePair<>> (2 answers) Closed 12 months ago.

Scenario

Having already read a post on this on the same site, which didn't work, I'm feeling a bit stumped but I'm sure I've done this before.

I have a Dictionary. I want to take the first 200 values from the Dictionary.

CODE

  Dictionary<int,SomeObject> oldDict = new Dictionary<int,SomeObject>();
  //oldDict gets pop开发者_Python百科ulated somewhere else.
  Dictionary<int,SomeObject> newDict = new Dictionary<int,SomeObject>();
  newDict = oldDict.Take(200).ToDictionary();

OBVIOUSLY, the take returns an IENumerable, so you have to run ToDictionary() to convert it back to a dictionary of the same type. HOWEVER, it just doesn't work, it wants some random key selector thing - or something? I have even tried just casting it but to no avail. Any ideas?


Try this:

newDict = oldDict.Take(200).ToDictionary(x => x.Key, x => x.Value);

Basically a dictionary allows you to iterate over key/value pairs; when you want to convert back to a dictionary, you have to say what to use as the key and what to use as the value.

However, I would question your code's correctness - because a dictionary doesn't have the concept of "the first 200 values". Don't rely on the ordering within a dictionary. This will basically give you some effectively-arbitrary 200 entries from within the dictionary.

What are you trying to do? What's your idea of the "first" 200 entries?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜