问题描述
以防万一你想知道这是怎么了,我正与来自实体框架的一些结果集。
Just in case you're wondering how this came up, I'm working with some resultsets from Entity Framework.
我有一个对象,它是一个的IEnumerable< IEnumerable的<字符串>>
;基本上,字符串列表的列表。
I have an object that is an IEnumerable<IEnumerable<string>>
; basically, a list of lists of strings.
我要为字符串的所有列表合并成字符串中的一个大名单。
I want to merge all the lists of strings into one big list of strings.
什么是做这在C#.NET的最好方法是什么?
What is the best way to do this in C#.net?
推荐答案
使用LINQ的方法的SelectMany:
Use the LINQ SelectMany method:
IEnumerable<IEnumerable<string>> myOuterList = // some IEnumerable<IEnumerable<string>>...
IEnumerable<String> allMyStrings = myOuterList.SelectMany(sl => sl);
要很清楚地了解这里发生了(因为我最讨厌的人认为这是某种巫术的思想,我觉得不好,其他一些人删了相同的答案):
To be very clear about what's going on here (since I hate the thought of people thinking this is some kind of sorcery, and I feel bad that some other folks deleted the same answer):
的SelectMany是的(静态方法,通过语法糖看起来像一个特定类型的实例方法)对的IEnumerable&LT ; T&GT;
。这需要你原来的枚举枚举和功能转换的每个项目为一个枚举。
SelectMany is an extension method ( a static method that through syntactic sugar looks like an instance method on a specific type) on IEnumerable<T>
. It takes your original enumeration of enumerations and a function for converting each item of that into a enumeration.
由于该项目的已的枚举,转换功能简单 - 只需返回输入(SL =&GT <$ C C $>; SL 表示取paremeter名为 SL
并返回)。随后的SelectMany提供了所有这些又是一个枚举,导致你的扁平化的文章。
Because the items are already enumerations, the conversion function is simple- just return the input (sl => sl
means "take a paremeter named sl
and return it"). SelectMany then provides an enumeration over each of these in turn, resulting in your "flattened" list..
这篇关于如何联合起来在IEnumerables的IEnumerable的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!