enes turan
enes turan

Reputation: 25

how to sort csv file with two columns in c#

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

Upvotes: 1

Views: 6428

Answers (4)

Tim Schmelter
Tim Schmelter

Reputation: 460108

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.

Upvotes: 3

shree.pat18
shree.pat18

Reputation: 21757

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.

Upvotes: 1

artm
artm

Reputation: 8584

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)

Upvotes: 1

user28470
user28470

Reputation: 429

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

Upvotes: 1

Related Questions