访问元素

时间:2012-03-07 15:39:24

标签: linq

鉴于从以下方面返回的数据:

public IEnumerable<IEnumerable<string>> ReadFile(string filename)
{
   List<List<string>> items;
   // Read entire file content into items.
   ...
   return items;
 }

如何检索/返回特定列?

public IEnumerable<string> GetColumnAtIndex(IEnumerable<IEnumerable<string>> items, int index)
{
    // THIS IS NOT WORKING...
    return (from row in items
              select row.ElementAt(index)).ToList();
}

预期用途示例:

var items = ReadFile(@"testdata.csv");
var singleColumn = GetColumnAtIndex(items, 2);

1 个答案:

答案 0 :(得分:0)

刚刚阅读了您的评论,即您的问题是您获得了ArgumentOutOfRangeException,那么最可能的原因是构成您的行的某些List<string>对象没有足够的元素在你要求的专栏中有一些东西。

例如,一个空行可能会解析为空List<string>或者在位置0只有一个""的行。如果您要尝试获取位置5处的所有条目,那么它会到达这一行会引发异常。

如果您有List<List<string>> items,并希望List<string>位于第0位,则可以执行此操作:

List<string> innerList = items[0];

如果您想要该列表中第0个位置的项目,您可以执行

string item = items[0][0];

除非我错过了你想要做的事情,否则你不需要使用linq。

哦,我已经意识到你可能想要每个外部列表的内部列表中的第n个项目......在这种情况下,你应该有什么工作,而且确实在我的测试用例中:

List<List<string>> foo = new List<List<string>>(){new List<string>(){"1","2","3","4","5"},new List<string>(){"6","7","8","9","0"}};
var output = (from row in foo
          select row.ElementAt(2)).ToList();
output.Dump();
相关问题