所以我将一个CSV文件读入C#并对其进行了一些操作,最终文件名为:retainedLines,类型为“var”。在将此文件写入硬盘之前,我想对其中的第二列进行排序。我试过这个例子: Sorting csv file 但它不起作用,我得到一个处理错误。 这是我坚持的代码的一部分:
String inputpath = textBox1.Text;
if (File.Exists(inputpath))
{
//MessageBox.Show(inputpath, outputpath);
var retainedLines = File.ReadAllLines(inputpath)
.Where((x, i) => i == 0
|| (x.Split(',')[1]).Contains(checkCritical())
|| (x.Split(',')[1]).Contains(checkWarning())
|| (x.Split(',')[1]).Contains(checkMajor())
|| (x.Split(',')[1]).Contains(checkClear())
);
if (inputpath.Equals(outputpath))
{
File.Delete(inputpath);
}
//here is where I want to sort the file alphabetically by second column
File.WriteAllLines(outputpath, retainedLines);
}
答案 0 :(得分:2)
您可以像这样进行排序:
retainedLines = retainedLines.OrderBy(line => line.Split(',')[1]);
但是我会重构第一个代码,所以每次都不会调用Split
方法进行过滤,而是:
var retainedLines = File.ReadAllLines(inputpath)
.Select(x => x.Split(','))
.Where((x, i) => i == 0
|| (x[1]).Contains(checkCritical())
|| (x[1]).Contains(checkWarning())
|| (x[1]).Contains(checkMajor())
|| (x[1]).Contains(checkClear())
)
.OrderBy(x => x[1])
.Select(parts => string.Join(",", parts);