Linq - 将一个 ILookup 转换为另一个 ILookup
这应该很简单,但我想不出一个好的方法。如何将一个 ILookup 转换为另一个 ILookup?例如,如何复制/克隆 ILookup,生成具有相同键和相同组的另一个 ILookup?
这是我蹩脚的尝试:
static ILookup<TKey, TValue> Copy<TKey, TValue>(ILookup<TKey, TValue> lookup)
{
return lookup
.ToDictionary(
grouping => grouping.Key,
grouping => grouping.ToArray())
.SelectMany(pair =>
pair
.Value
.Select(value =>
new KeyValuePair<TKey, TValue>(pair.Key, value)))
.ToLookup(pair => pair.Key, pair => pair.Value);
}
有人可以改进吗?
——布莱恩
This should be simple, but I can't think of a good way to do it. How do you transform an ILookup into another ILookup? For example, how would you copy/clone an ILookup, producing another ILookup with the same keys and same groups?
Here's my lame attempt:
static ILookup<TKey, TValue> Copy<TKey, TValue>(ILookup<TKey, TValue> lookup)
{
return lookup
.ToDictionary(
grouping => grouping.Key,
grouping => grouping.ToArray())
.SelectMany(pair =>
pair
.Value
.Select(value =>
new KeyValuePair<TKey, TValue>(pair.Key, value)))
.ToLookup(pair => pair.Key, pair => pair.Value);
}
Can anyone improve this?
-- Brian
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个怎么样:
How about this:
这是你想要的吗?
当然,如果您想以某种方式转换这些值,也许您想要这样的东西:
请注意,此方法将中间值保存在
KeyValuePair
中,作为值类型,它存储在堆栈中,因此不需要任何中间内存分配。我分析了一个测试,该测试创建一个包含 100 个键的Lookup
,每个键有 10,000 个项目(总共 1,000,000 个)。Lookup
进行 1610 次分配。SelectMany
调用中每个委托的分配以及每个键的枚举器的分配)。KeyValuePair
复制它会进行 1,001,712 次分配(复制所需的所有分配每项加 1)。从 CPU 角度来看,即使每个键有 100,000 个元素,两种复制方法之间的
Lookup
性能也是相同的。每个键有 1,000,000 个元素,两种方法的性能有所不同:KeyValuePair
复制 5.9 秒,Does this do what you want?
Of course, if you want to transform the values somehow, maybe you want something like this:
Note that this method holds intermediate values in a
KeyValuePair
which, being a value type, is stored on the stack and thus doesn't require any intermediate memory allocations. I profiled a test that creates aLookup<int,int>
with 100 keys, each having 10,000 items (for a total of 1,000,000).Lookup
does 1610 allocations.SelectMany
call and one for the enumerator for each key).KeyValuePair
does 1,001,712 allocations (all the allocations required to copy plus one for each item).CPU-wise, even with 100,000 elements per key in the
Lookup
performance between the two copying methods was identical. With 1,000,000 elements per key, the performance was different between the two methods:KeyValuePair