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

时间:2014-10-10 09:23:03

标签: c# linq sorting csv

我的csv文件有14列和~800.000行。我必须按第10列排序csv orderby第3列。 我使用下面的代码,但只按第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; ..

4 个答案:

答案 0 :(得分:1)

您必须使用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.ReadLines在这种情况下效率高于File.ReadAllLines

答案 1 :(得分:0)

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

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

            }
            ).OrderBy(x => x.SortKey).ThenBy(x => x.Line);

答案 2 :(得分:0)

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)

答案 3 :(得分:0)

试试这个:

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

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