如何用c中的两列对csv文件进行排序#
问题描述:
我的csv文件有14列和~800.000行。我必须按照第10栏排序,然后按第3栏排序。 我使用下面的代码,但种种仅10列如何用c中的两列对csv文件进行排序#
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; ..
答
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)
答
您需要的第一排序依据后使用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);
基本上添加第二排序标准,然后排序按照指定的顺序。
答
你必须使用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
更有效。
它的作品谢谢你。其实这很容易。 – eneseto 2014-10-10 09:37:58