如何将IEnumerable<IEnumerable<T>>转换为List<string>?

11

我还不太理解这个 T 是什么意思。我需要将以下结果转换为列表。

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();

1
没有任何侮辱的意思,但是你理解自己的代码吗? - gunr2171
1
我不理解 GetPermutations 部分,因为我没有编写它。这就是为什么我在问 @gunr2171 :D - Furkan Gözükara
2个回答

22
任何 IEnumerable<IEnumerable<T>>,我们可以简单地调用 SelectMany

例如:

IEnumerable<IEnumerable<String>> lotsOStrings = new List<List<String>>();
IEnumerable<String> flattened = lotsOStrings.SelectMany(s => s);

2

由于lstShuffle实现了IEnumerable<string>,您可以将T在心中替换为string:您正在调用IEnumerable<IEnumerable<string>> GetPermutations(IEnumerable<string> items)

正如Alexi所说,SelectMany(x => x)是将IEnumerable<IEnumerable<T>>展平为IEnumerable<T>的最简单方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接