[英]How to sort a text file in alphabetical order using c#
it prints all the names from last name to fist in the text file but i am stuck trying to print it in alphabetical order by last name它打印文本文件中从姓氏到拳头的所有名称,但我试图按姓氏的字母顺序打印它
here is the code i have so far:这是我到目前为止的代码:
namespace cse1302_Lecture18_FileIO_Prez
{
class Program
{
static void Main(string[] args)
{
StreamReader sr = new StreamReader("NameInput.txt"); //if file in bin/debug
char[] delims = {','};
//string[] names = {"",""};
while(!sr.EndOfStream)
{
string data_line = sr.ReadLine();
//names = data_line.Split(delims);
Console.WriteLine(data_line);
}
sr.Close();
}
}
}
Try using LINQ.尝试使用 LINQ。 I've assumed here that you file contains two fields per line delimited with a comma, where the first is the First Name and the second the Surname.
我在这里假设您的文件每行包含两个字段,用逗号分隔,其中第一个是名字,第二个是姓氏。
var lines = System.IO.File.ReadLines("NameInput.txt");
var linesOrderedBySurname = lines.OrderBy((p) => p.Split(',')[1]).ToList();
First store the names into a list
, then sort them based on last name
like:首先将名称存储到
list
,然后根据last name
对它们进行排序,例如:
var names = new List<string>();
while(!sr.EndOfStream)
{
names.Add(sr.ReadLine());
}
names.Sort((x, y) => x.Split(',')[1].CompareTo(y.Split(',')[1]));
Then just display list items in the console.然后只在控制台中显示列表项。
foreach(var name in names)
Console.WriteLine(name);
This assumes that last name comes after first name and they are delimited with a comma .这假设姓氏在名字之后,并且它们用逗号分隔。
Try to use File.ReadAllLines
instead of StreamReader
you need to load all lines of the file and then use LINQ
to order them尝试使用
File.ReadAllLines
而不是StreamReader
您需要加载文件的所有行,然后使用LINQ
对它们进行排序
static void Main(string[] args)
{
var lastNames = File.ReadAllLines("yourtxtfile.txt").OrderBy(line => line.Split(',')[1]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.