What i need to do is read a specific text file and pull out the entire column based on a string.
So if my string was parkingfee I would pull out whatever column in my | delimited file that header row matched the word parking开发者_JAVA技巧fee
This should do the trick for you. To do what you'd want, you could do this:
foreach(string val in GetColumnValues(fileName, "parkingfee", "|")
{
...
}
Here's the function:
public static IEnumerable<string> GetColumnValues(string fileName, string columnName, string delimiter)
{
using (System.IO.StreamReader reader = new System.IO.StreamReader(fileName))
{
string[] delim = new string[] { delimiter };
string[] columns = reader.ReadLine().Split(delim, StringSplitOptions.None);
int column = -1;
for (int i = 0; i < columns.Length; i++)
{
if (string.Compare(columns[i], columnName, true) == 0)
{
column = i;
break;
}
}
if (column == -1) throw new ArgumentException("The specified column could not be found.");
while (reader.BaseStream.Position < reader.BaseStream.Length)
{
string[] line = reader.ReadLine().Split(delim, StringSplitOptions.None);
if (line.Length > column) yield return line[column];
}
}
}
精彩评论