我有一个包含 1000 行(每行大约 30 列)的文本文件,需要根据某些条件提取所需的行。
使用下面的代码我已经准备好从文本文件到列表的集合
string[] records = File.ReadAllLines(path);
List<string> listOfStr = new List<string>(records);
我需要查询每一行的特定列...如果符合条件...我需要该记录...如何使用 linq 执行此操作?或任何其他方法?
您应该File.ReadLines
改用 which 流式传输行,而不是先将所有行加载到内存中。此外,您在这里创建了两个内存中的集合:
string[] records = File.ReadAllLines(path);
List<string> listOfStr = new List<string>(records);
这在内存消耗方面效率更高:
var matchingLines = File.ReadLines(path)
.Select(l => new{ Parts = l.Split(), Line = l })
.Where(x => x.Parts.ElementAtOrDefault(9) == yourSearch)
.Select(x => x.Line);
foreach (string line in matchingLines)
Console.WriteLine(line);
您还没有提到分隔每列的分隔符,我使用了空格,l.Split(',')
将用逗号分隔。Enumerable.ElementAtOrDefault(9)
如果可用,则返回第 10 列,否则null
返回。
如果行由逗号分隔,请尝试以下操作:
int indexCol = 0; //the index of the col you want to look into
string search = string.Empty; //what you want to search in the column
string lineResult = listOfStr.FirstOfDefault(x=> x.split(",")[indexCol].Contains(search));
其他
string search = string.Empty;
foreach (string line in listOfSrt)
{
string[] inCols = line.Split("\t");
if (inCols[0].Contains(search))
{
Console.WriteLine(line);
}
}
string[] records = File.ReadAllLines(path);
List<string> listOfStr = new List<string>(records);
List<string> listOfMatches = listOfStr.Where(str => str[YOUR TEST COLUMN].Equals([YOUR TEST VALUE])).ToList();
首先将行拆分为列:
List<string[]> listOfStr = records.Select(s => s.Split('\t')).ToList();
您可以使用该Where
方法过滤条件。
例如,这会过滤掉第五列为的所有行"Hello"
:
List<string[]> result = listOfStr
.Where(s => s[4] == "Hello")
.ToList();