我有一个包含 1000 行(每行大约 30 列)的文本文件,需要根据某些条件提取所需的行。
使用下面的代码,我已将文本文件中的集合准备到列表中
string[] records = File.ReadAllLines(path);
List<string> listOfStr = new List<string>(records);
我需要查询每行的特定列...如果符合条件...我需要该记录... 我如何使用 linq 来做到这一点?或者任何其他方法?
最佳答案
您应该使用 File.ReadLines
来流式传输行,而不是首先将所有行加载到内存中。此外,您将在此处创建两个内存中集合:
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
。
关于c# - List<String[]> - 需要有关如何从 String[] 中提取记录的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17536892/