我的文件中的行内容格式如下:
Ref.,ID,Firstname,Secondname,City
Run Code Online (Sandbox Code Playgroud)
这是我的文件:
1,4234,Firstname1,Secondname1,City1
2,5647,Firstname2,Secondname2,City2
3,1657,Firstname3,Secondname3,City3
4,3898,Firstname4,Secondname4,City4
Run Code Online (Sandbox Code Playgroud)
现在我想按 ID 对其进行排序,然后将其再次放入文件中,如下所示:
3,1657,Firstname3,Secondname3,City3
4,3898,Firstname4,Secondname4,City4
1,4234,Firstname1,Secondname1,City1
2,5647,Firstname2,Secondname2,City2
Run Code Online (Sandbox Code Playgroud)
注意:整行是一个字符串变量。
那么有没有办法做到这一点?
这是我的代码:
int counter = 0;
string ln; //Each line in file per loop Ex:1,8957,Firstname,lastname,city
using (StreamReader file = new StreamReader(filePath))
{
Console.WriteLine("Records in the file" + Environment.NewLine);
Console.WriteLine("Ref,First name,Second name,City" + Environment.NewLine);
while ((ln = file.ReadLine()) != null)
{
Console.WriteLine(ln + Environment.NewLine);
/*
So here i need to sort the lines in the file, which written hard coded in the file before spliting it.
*/
//split the current line (comma separated) into array of strings with Ref,Id,first name, last name and city respectively
listLineElements = ln.Split(',').ToList();
//get city (4th elemnt in the array)
Student student = new Student(listLineElements[0], listLineElements[1], listLineElements[2], listLineElements[3], listLineElements[4]);
//for each line call addIndex to check whether index is new? or add it to the secondary index list?
addIndex(student.getCity(), ln);
counter++; //counter for the number of read lines
}
file.Close();
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
string[] lines = File.ReadAllLines(filePath);
string[] sortedLines = lines
.Select(s => new
{
Line = s,
SortKey = int.Parse(s.Split(',')[1])
})
.OrderBy(sl => sl.SortKey)
.Select(sl => sl.Line)
.ToArray();
File.WriteAllLines(filePath, sortedLines);
Run Code Online (Sandbox Code Playgroud)
演示小提琴:https : //dotnetfiddle.net/g8M8nQ
| 归档时间: |
|
| 查看次数: |
55 次 |
| 最近记录: |