【问题标题】:Dynamically projecting with LINQ使用 LINQ 进行动态投影
【发布时间】:2014-07-25 15:37:25
【问题描述】:

给定

(1) 一个数据库表,存储为列表列表。表格的行和列大小未定义。

List<List<string>> table = new List<List<string>>();

例如:

table.Add(new List<string>() { "a1", "b1", "c1", "d1", "e1" });
table.Add(new List<string>() { "a2", "b2", "c2", "d2", "e2" });
table.Add(new List<string>() { "a3", "b3", "c3", "d3", "e3" });
| a1 | b1 | c1 | d1 | e1 | | a2 | b2 | c2 | d2 | e2 | | a3 | b3 | c3 | d3 | e3 |

(2) 整数列表。这些整数类似于数据库列的索引(从零开始),例如:

List<int> indexes = new List<int>() { 1, 3, 4 };

问题

我的目标是从table 投影那些索引出现在列表indexes 中的列。鉴于上述示例,结果应该是:

| b1 | d1 | e1 | | b2 | d2 | e2 | | b3 | d3 | e3 |

当前解决方案

我能想到的最好办法是遍历所有行,如下所示:

List<List<string>> subtable = new List<List<string>>();
for (int index = 0; index < table.Count; index++)
{
    subtable.Add(table[index].Where((t, i) => indexes.Contains(i)).ToList());
}

请求

如果可能的话,一个更优雅的解决方案。

【问题讨论】:

    标签: c# linq projection


    【解决方案1】:

    这个呢:

    List<List<string>> subtable =
        table.Select(row => indexes.Select(i => row[i]).ToList()).ToList();
    

    如果您需要检查数组边界,可以这样做:

    List<List<string>> subtable =
        table.Select(row => indexes.Where(i => i >= 0 && i < row.Count)
                                   .Select(i => row[i]).ToList()).ToList();
    

    或者,如果您更喜欢查询语法:

    List<List<string>> subtable =
        (from row in table
         select
         (from i in indexes
          where i >= 0 && i < row.Count
          select row[i]
         ).ToList()
        ).ToList();
    

    【讨论】:

    • 这正是我想要的。谢谢。
    【解决方案2】:

    选择所有行,然后为每一行过滤掉不在索引列表中的列:

    var subtable = table
         .Select(row => row.Where((value, colIndex) => indexes.Contains(colIndex)))
         .ToList();
    

    【讨论】:

      【解决方案3】:

      如果您只想打印,则无需这样的查询就可以更简单(也更高效):

              List<List<string>> table = new List<List<string>>();
              table.Add(new List<string>() { "a1", "b1", "c1", "d1", "e1" });
              table.Add(new List<string>() { "a2", "b2", "c2", "d2", "e2" });
              table.Add(new List<string>() { "a3", "b3", "c3", "d3", "e3" });
      
              List<int> indexes = new List<int>() { 1, 3, 4 };
      
              for (int index = 0; index < table.Count; index++)
              {
                  foreach (var columnIndex in indexes)
                      Console.Write(table[index][columnIndex] +" ");
      
                  Console.WriteLine();
              }
      
              Console.ReadLine();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-21
        • 2022-01-18
        • 2019-12-15
        • 2012-04-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多