C# 自定义字典获取 - 从 IEnumerable 转换回来

发布于 2024-08-27 05:47:35 字数 533 浏览 5 评论 0原文

场景

我已经在同一网站上读过一篇关于此问题的文章,但没有成功,我感觉有点困惑,但我确信我以前已经这样做过。

我有一本字典。 我想从字典中获取前 200 个值。

代码

  Dictionary<int,SomeObject> oldDict = new Dictionary<int,SomeObject>();
  //oldDict gets populated somewhere else.
  Dictionary<int,SomeObject> newDict = new Dictionary<int,SomeObject>();
  newDict = oldDict.Take(200).ToDictionary();

显而易见,take 返回一个 IEnumerable,因此您必须运行 ToDictionary() 将其转换回相同类型的字典。然而,它就是不起作用,它需要一些随机键选择器的东西 - 或者什么?我什至尝试过只是铸造它,但没有成功。 有什么想法吗?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

中二柚 2024-09-03 05:47:35

试试这个:

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

基本上,字典允许您迭代键/值对;当您想要将转换回为字典时,您必须说明使用什么作为键以及使用什么作为值。

但是,我会质疑你的代码的正确性 - 因为字典没有“前 200 个值”的概念。不要依赖字典中的顺序。这基本上会为您提供字典中的一些有效的任意 200 个条目。

你想做什么?您对“前”200 个条目有何看法?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文