如何在c#中用两列对csv文件进行排序

本文关键字:csv 两列 文件 排序 | 更新日期: 2023-09-27 18:26:05

我的csv文件有14列,大约有800.000行。我必须先按第10列,然后按第3列对csv排序。我使用以下代码,但只按第10列排序

            string filePath = "D:''csv.csv";
            string[] lines = File.ReadAllLines(filePath, Encoding.Default);
            var data = lines.Skip(1);
            var sorted = data.Select(line => new
            {
                SortKey = Int32.Parse(line.Split(';')[9]),
                 Line = line
            }
            ).OrderBy(x => x.SortKey).Select(x => x.Line);
            File.WriteAllLines("D:''sortedCsv.csv", lines.Take(1).Concat(sorted), Encoding.Default);

我的csv喜欢

  • col1;col2;col3;。。。。。。;col10
  • abc;fds;123456;123
  • def;dsa;12435。。。。124

如何在c#中用两列对csv文件进行排序

您必须使用OrderBy(...).ThenBy(...):

var lines = File.ReadLines(filePath, Encoding.Default);
var data = lines
           .Skip(1)
           .Select(l => new{Fields = l.Split(';'), Line = l})
           .Where(x => x.Fields.Length == 14 && x.Fields[9].All(Char.IsDigit))
           .OrderBy(x => int.Parse(x.Fields[9]))
           .ThenBy(x => x.Fields[2])
           .Select(x => x.Line);
File.WriteAllLines("D:''sortedCsv.csv", lines.Take(1).Concat(data), Encoding.Default);

注意,在这种情况下,File.ReadLinesFile.ReadAllLines更有效率。

var sorted = data.Select(line => new
{
    SortKey = Int32.Parse(line.Split(';')[9]),
    SortKeyThenBy = Int32.Parse(line.Split(';')[2]),
    Line = line
}
).OrderBy(x => x.SortKey).ThenBy(x => x.SortKeyThenBy)

您需要在第一个OrderBy 之后使用thenBy

            var sorted = data.Select(line => new
            {
                SortKey = Int32.Parse(line.Split(';')[9]),
                 Line = line
            }
            ).OrderBy(x => x.SortKey).ThenBy(x => x.Line);

试试这个:

var sorted = data.Select(line => new
        {
            SortKey = Int32.Parse(line.Split(';')[9]),
            SortKey2 = line.Split(';')[2],
             Line = line
        }
        ).OrderBy(x => x.SortKey).ThenBy(x=>x.SortKey2).Select(x => x.Line);

基本上添加第二个排序标准,然后按照指定的顺序进行排序。