如何跳过读取和排序C#的第一行

时间:2013-05-28 20:15:40

标签: c#

我有这个代码用于排序csv文件。如何从读取和排序中跳过第一行文件,因为第一行具有列的名称。该文件看起来像:

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);
}

3 个答案:

答案 0 :(得分:7)

File.ReadLines(@"C:\....dat.csv")
.Skip(1)

答案 1 :(得分:1)

要扩展Raphaël的解决方案,您可以使用Memoize函数来保留标题行,但对其余部分进行排序。微软的Ix-Main nuget包有其它非常有用的扩展,或者你可以使用ReadAllLines()或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);

答案 2 :(得分:0)

使用文件助手:

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);