Given data returned from:
public IEnumerable<IEnumerable<string>> ReadFile(string filename)
{
List<List<string>> items;
// Read entire file content into items.
...
return items;
}
How can I retrieve/return a specific column?
public IEnumerable<string> GetColumnAtIndex(IEnumerable<IEnumerable<string>> items, int index)
{
// THIS IS NOT WORKING...
return (from row in items
select row.ElementAt(index)).ToList();
}
Example intended use:
var items = ReadFile(@"testdata.csv");
var singleColumn = GetColumnAtIndex(items, 2);
Having just read your comment that your problem is that you are getting an
ArgumentOutOfRangeExceptionthen the most likely cause for that is that some of theList<string>objects that make up your rows do not have enough elements to have somethign in the column you have asked for.For example an empty row might parse to an empty
List<string>or one with only a""at position 0. If you were to try to get all the entries at position 5 then whjen it got to this row it would throw that exception.If you have
List<List<string>> itemsand you want to get theList<string>in the 0th position you can do this:If you want the item that is in the 0th position of that list you can just do
You don’t need to use linq unless I have missed what you are trying to do.
Oh, I’ve realised you might want the nth item from the inner list for every one of the outer lists… In that case what you have should work and indeed does in my test case: