![](/img/trans.png)
[英]How to convert an IEnumerable<IEnumerable<T>> to a IEnumerable<T>
[英]How to convert IEnumerable<IEnumerable<T>> to List<string>?
我真的不明白这件事。 我需要将以下结果转换为List
private void generateKeywords_Click(object sender, RoutedEventArgs e)
{
string srText = new TextRange(
txthtmlsource.Document.ContentStart,
txthtmlsource.Document.ContentEnd).Text;
List<string> lstShuffle = srText.Split(' ')
.Select(p => p.ToString().Trim().Replace("\r\n", ""))
.ToList<string>();
lstShuffle = GetPermutations(lstShuffle)
.Select(pr => pr.ToString())
.ToList();
}
public static IEnumerable<IEnumerable<T>> GetPermutations<T>(
IEnumerable<T> items)
{
if (items.Count() > 1)
{
return items
.SelectMany(
item => GetPermutations(items.Where(i => !i.Equals(item))),
(item, permutation) => new[] { item }.Concat(permutation));
}
else
{
return new[] { items };
}
}
下面这一行失败,因为我无法正常转换。 我的意思是不是错误,但也不是字符串列表
lstShuffle = GetPermutations(lstShuffle).Select(pr => pr.ToString()).ToList();
对于任何IEnumerable<IEnumerable<T>>
我们可以简单地调用SelectMany
。
例:
IEnumerable<IEnumerable<String>> lotsOStrings = new List<List<String>>();
IEnumerable<String> flattened = lotsOStrings.SelectMany(s => s);
由于lstShuffle
实现了IEnumerable<string>
,你可以在心理上用string
替换T
:你正在调用IEnumerable<IEnumerable<string>> GetPermutations(IEnumerable<string> items)
。
正如Alexi所说, SelectMany(x => x)
是将IEnumerable<IEnumerable<T>>
IEnumerable<T>
为IEnumerable<T>
的最简单方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.