【问题标题】:Efficient way to convert <List<List<StrongType.String>> to List<string> [duplicate]将 <List<List<StrongType.String>> 转换为 List<string> 的有效方法 [重复]
【发布时间】:2016-05-27 12:15:08
【问题描述】:

我有一个由List&lt;List&lt;MyType&gt;&gt; 组成的集合,我正在考虑从中创建一个字符串列表。

MyType 在哪里:

class MyType
{
   public string Description {get;set;}
}

我想得到一个扁平的字符串列表,以一种有效的方式使用 linq,而不使用 for 循环。

属性上方是我正在使用的描述。

【问题讨论】:

  • 什么意思是“没有for循环的高效”。请注意,为了完成此任务,您必须以任何方式迭代列表,因此无论您如何美化代码,迭代都将保留。
  • AFAIK 迭代列表的最有效(就速度而言)方法是使用老式的索引 for 循环。我想知道你为什么不想使用它。
  • @MarioVernari 并不总是正确的,如果使用正确,迭代器会很棒
  • @bto.rdz 请澄清您对“正确”的含义。你能举一些迭代器比索引器快的例子吗?
  • @MarioVernari 在我的示例中,您在内存中只有 1 个列表,如果您使用索引器,您有 2 个选项,1) 使用嵌套的 for,在我看来,与一个 linq 查询,2) 将元素复制到第二个列表中,并使用双倍内存。

标签: c# linq


【解决方案1】:

怎么样

List<List<MyType>> list = //your list....

var result = list.SelectMany(x => x.Select(y => y.Description));

【讨论】:

    【解决方案2】:

    假设您的List&lt;List&lt;MyType&gt;&gt; 被命名为MyList

    List<string> strings = (from myTypes in MyList 
                                        from myType in myTypes 
                                        select myType.Description
                            ).ToList();
    

    如果你想避免一次重复:

    HashSet<string> myHashSet = new HashSet<string>();
    
    foreach (MyType myType in MyList.SelectMany(myTypes => myTypes))
    {
        myHashSet.Add(myType.Description);
    }
    

    【讨论】:

      【解决方案3】:

      你可以像这样使用SelectMany

      var list = SelectMany(x => x).Select(x => x.Description).ToList();
      

      【讨论】:

        【解决方案4】:
        yourList.SelectMany(x => x.Select(y => y.Description)).ToList();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-17
          • 2018-08-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多