【问题标题】:LINQ - Get all items in a List within a List?LINQ - 获取列表中的所有项目?
【发布时间】:2011-03-17 01:48:31
【问题描述】:

我目前正在学习 LINQ 的学习曲线,我真的需要一些帮助。我不知道我想要的是否可能,但如果我必须下注,我敢打赌。

我目前有一个名为 _tables 的对象列表,其中每个对象都有另一个通过属性“索引”公开的对象列表。本质上,我想最终得到一个列表,其中包含所有 _tables 中的所有索引。

这是我目前所拥有的:

var indexes = from TableInfo tab
              in _tables
              where tab.Indexes.Count > 0
              select tab.Indexes;

不幸的是,这似乎给了我另一个列表列表,但仅在索引列表包含多个值的情况下...有什么方法可以在没有循环的情况下将所有这些列表放在一起吗?

【问题讨论】:

    标签: c# .net linq list


    【解决方案1】:

    您想使用SelectMany 扩展方法。

    _tables.SelectMany(t => t.Indexes)
    

    【讨论】:

    【解决方案2】:

    除了 tbischel 的回答之外,您要查找的查询表达式版本如下。

    var indexes = from TableInfo tab in _tables 
                  from index in tab.Indexes
                  select index;
    

    【讨论】:

      【解决方案3】:

      你不需要 where 子句,你也不应该告诉它标签是什么

      您将需要使用 SelectMany

      var indexes = (from tab in _tables).SelectMany(t => t.Indexes)
      

      或者你可以这样做

         var indexes = from tab in _tables
                        from t in tab.Indexes
                        select t;
      

      那应该是比较熟悉的syntaz

      【讨论】:

        【解决方案4】:
        var rows = from item in table select item;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-18
          • 1970-01-01
          • 2019-11-02
          • 2013-12-07
          相关资源
          最近更新 更多