1

my csv files have 14 columns and ~800.000 lines. I must sort csv orderby 10th column thenby 3rd column. I use below code but sorts by only 10th column

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

my csv likes

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

4 Answers 4

3

You have to use 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);

Note that File.ReadLines is more efficient than File.ReadAllLines in this case.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

you need to use thenBy after the first OrderBy

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

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

Comments

1

Try this:

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

Basically add your second sorting criterion and then sort in the specified order.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.