简体   繁体   English

使用LINQ将IEnumerable映射到ILookup的紧凑方法

[英]Compact way to map an IEnumerable to an ILookup with LINQ

A situation I've found myself in a few times: I have an IEnumerable<T> , and a function map that maps an instance of T to an IEnumerable<U> . 我已经几次发现自己的情况:我有一个IEnumerable<T> ,以及一个将T的实例映射到IEnumerable<U>的函数map I want to produce an ILookup<T, U> defined by that map. 我想生成该映射定义的ILookup<T, U>

This seems like a pretty common use case, but I haven't found a compact way to produce the lookup. 这似乎是一个很普通的用例,但是我还没有找到一种生成查询的紧凑方法。 In particular, enumT.ToLookup( t=>t, t=>map(t)) produces an ILookup<T, IEnumerable<U>> . 特别是, enumT.ToLookup( t=>t, t=>map(t))产生ILookup<T, IEnumerable<U>>

Simply use SelectMany to flatten the sequence out before calling ToLookup . 在调用ToLookup之前,只需使用SelectMany展平序列即可。

var lookup = sequence.SelectMany(key => Foo(key), (key, value) => new { key, value, })
    .ToLookup(pair => pair.key, pair => pair.value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM