[英]If I have a text file with a list of names, how can I sort this list by their last names first using C#?
我正在嘗試編寫一個程序,它將讀取一個文本文件,列出的名稱列表如
邁克爾·喬丹
科比·布萊恩特
拉里伯德
勒布朗·詹姆斯
我編寫了代碼來打開文件並重寫文件並將其包含在內。
加載后,如何按姓氏排序此列表,然后按名字排序?
List<string> cstrName = new List<string>();
private void Sorter_Load(object sender, EventArgs e)
{
try
{
//Load the array with the data in the file
FileStream nameFile = new FileStream("input.txt",FileMode.Open);
StreamReader nameStreamReader = new StreamReader(nameFile);
while (nameStreamReader.Peek() != -1)
{
cstrName.Add(nameStreamReader.ReadLine());
}//End Loop
nameFile.Close(); //Close file
}
//Sets an error message if there is an issue opening the file
catch (Exception ex)
{
MessageBox.Show("Error Opening File. Data not loaded " +
ex.Message,"File Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
private void btnSortByName_Click(object sender, EventArgs e)
{
{
cstrName.Sort();
}
//display names in a list box
displayNames();
}
private void button1_Click(object sender, EventArgs e)
{
System.IO.File.WriteAllLines("input2.txt", cstrName);
this.Close();
}
交換你的cstrName.Sort();
對於
cstrName = cstrName.OrderBy(x => x.Split(' ').Last()).ToList();
確保你有Using System.Linq;
在您的文件的頂部。
它通過字符串中的最后一個單詞對cstrName進行排序(通過將字符串拆分為空格'來計算單詞)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.