【问题标题】:How to convert IEnumerable<IEnumerable<T>> to List<string>?如何将 IEnumerable<IEnumerable<T>> 转换为 List<string>?
【发布时间】:2013-06-06 02:05:21
【问题描述】:

我还真不明白这个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();

【问题讨论】:

  • 无意侮辱,但您了解您的代码的作用吗?
  • 我不理解 GetPermutations 部分,因为我没有对其进行编码。这就是我问的原因:D @gunr2171

标签: c# linq ienumerable


【解决方案1】:

对于任何IEnumerable&lt;IEnumerable&lt;T&gt;&gt;,我们可以简单地调用SelectMany

例子:

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

【讨论】:

    【解决方案2】:

    由于lstShuffle 实现了IEnumerable&lt;string&gt;,您可以将T 替换为string:您正在调用IEnumerable&lt;IEnumerable&lt;string&gt;&gt; GetPermutations(IEnumerable&lt;string&gt; items)

    正如 Alexi 所说,SelectMany(x =&gt; x) 是将IEnumerable&lt;IEnumerable&lt;T&gt;&gt; 扁平化为IEnumerable&lt;T&gt; 的最简单方法。

    【讨论】:

      猜你喜欢
      • 2018-08-04
      • 2012-02-24
      • 1970-01-01
      • 2021-12-02
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多