C# 如何从读取和排序C中跳过第一行#
我有这个代码用于排序csv文件。如何从读取和排序中跳过文件的第一行,因为se第一行有列的名称。该文件看起来像:C# 如何从读取和排序C中跳过第一行#,c#,C#,我有这个代码用于排序csv文件。如何从读取和排序中跳过文件的第一行,因为se第一行有列的名称。该文件看起来像: ID Name Surname Age Salary 1 John Asben 33 1000 2 Adam Smith 22 1200 代码是: private void buttonSortSave_Click(object sender, EventArgs e) { var sorted = File.ReadLines(@"C:\....
ID Name Surname Age Salary
1 John Asben 33 1000
2 Adam Smith 22 1200
代码是:
private void buttonSortSave_Click(object sender, EventArgs e)
{
var sorted =
File.ReadLines(@"C:\....dat.csv")
.Select(line => new
{
SortKey = Int32.Parse(line.Split(',')[3]),
Line = line
})
.OrderBy(x => x.SortKey)
.Select(x => x.Line);
File.WriteAllLines(@"C:\sorteddata.csv", sorted);
}
使用文件帮助程序:
FileHelpers.CsvOptions options = new FileHelpers.CsvOptions("ImportRecord", ',', file);
options.HeaderLines = 0;
FileHelpers.CsvEngine engine = new FileHelpers.CsvEngine(options);
//read header
engine.Options.IgnoreFirstLines = 0;
DataTable header = engine.ReadStringAsDT(FileHelpers.CommonEngine.RawReadFirstLines(file, 1));
//read the rest of the data without the header
engine.Options.IgnoreFirstLines = 1;
DataTable data = engine.ReadFileAsDT(file);
使用文件帮助程序:
FileHelpers.CsvOptions options = new FileHelpers.CsvOptions("ImportRecord", ',', file);
options.HeaderLines = 0;
FileHelpers.CsvEngine engine = new FileHelpers.CsvEngine(options);
//read header
engine.Options.IgnoreFirstLines = 0;
DataTable header = engine.ReadStringAsDT(FileHelpers.CommonEngine.RawReadFirstLines(file, 1));
//read the rest of the data without the header
engine.Options.IgnoreFirstLines = 1;
DataTable data = engine.ReadFileAsDT(file);
要扩展Raphaël的解决方案,可以使用Memoize函数保留标题行,但对其余行进行排序。Microsoft的Ix Main nuget软件包中有其他非常有用的扩展,或者您可以使用ReadAllLines()或ToArray():
要扩展Raphaël的解决方案,可以使用Memoize函数保留标题行,但对其余行进行排序。Microsoft的Ix Main nuget软件包中有其他非常有用的扩展,或者您可以使用ReadAllLines()或ToArray():
使用无需使用现有的
Select().OrderBy().Select()
。OrderBy
方法采用选择器。使用该选项可以获得适当的值进行排序。然后,您可以删除另外两个Select
方法。使用您拥有的Select().OrderBy().Select()
。OrderBy
方法采用选择器。使用该选项可以获得适当的值进行排序。然后,您可以删除另外两个Select
方法。操作系统无论如何都会缓存该文件页,因此您可以在不记忆该文件的情况下执行该操作,并且不太可能看到任何问题。请注意,如果文件大小非常小,则使用ReadAllLines
或ToArray
很容易导致问题。OrderBy
内部的存储开销为ToArray
,因此,虽然额外的ToArray
肯定会增加内存使用量,但除非它是一个大文件,否则可能不会那么糟糕。请记住,字符串不会被复制,因此不会产生100%的开销Memoize
将消除所有额外的开销,而且仍然不需要读取文件两次,这就是为什么我建议将其置于ToArray
之上。操作系统无论如何都会缓存该文件页,因此您可以在不进行Memoize的情况下执行此操作,并且不太可能看到任何问题。请注意,如果文件大小非常小,则使用ReadAllLines
或ToArray
很容易导致问题。OrderBy
内部的存储开销为ToArray
,因此,虽然额外的ToArray
肯定会增加内存使用量,但除非它是一个大文件,否则可能不会那么糟糕。请记住,字符串不会被复制,因此不会产生100%的开销Memoize
将消除所有额外的开销,而且仍然不需要读取文件两次,这就是为什么我建议将其置于ToArray
之上。
var items = File.ReadLines(@"C:\....dat.csv").Memoize(2);
var sorted = items.Take(1)
.Concat(items.Skip(1).OrderBy(line => Int32.Parse(line.Split(',')[3])));
File.WriteAllLines(@"C:\sorteddata.csv", sorted);