【发布时间】: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 中的列。鉴于上述示例,结果应该是:
当前解决方案
我能想到的最好办法是遍历所有行,如下所示:
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