Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用c按字母顺序对文本文件排序_C#_Sorting - Fatal编程技术网

C# 如何使用c按字母顺序对文本文件排序

C# 如何使用c按字母顺序对文本文件排序,c#,sorting,C#,Sorting,它在文本文件中打印从姓氏到拳头的所有名字,但我一直在按姓氏的字母顺序打印 以下是我目前掌握的代码: namespace cse1302_Lecture18_FileIO_Prez { class Program { static void Main(string[] args) { StreamReader sr = new StreamReader("NameInput.txt"); //if file in bin/d

它在文本文件中打印从姓氏到拳头的所有名字,但我一直在按姓氏的字母顺序打印

以下是我目前掌握的代码:

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();
        }
    }

}

尝试使用LINQ。这里我假设您的文件每行包含两个字段,用逗号分隔,其中第一个字段是名字,第二个字段是姓氏

var lines = System.IO.File.ReadLines("NameInput.txt");
var linesOrderedBySurname = lines.OrderBy((p) => p.Split(',')[1]).ToList();

首先将姓名存储到列表中,然后根据姓氏对其进行排序,如:

这假设姓氏在名字之后,并且用逗号分隔。

尝试使用而不是StreamReader您需要加载文件的所有行,然后使用LINQ对它们进行排序

 static void Main(string[] args)
            {
                var lastNames = File.ReadAllLines("yourtxtfile.txt").OrderBy(line => line.Split(',')[1]);    
            }
foreach(var name in names)
    Console.WriteLine(name);
 static void Main(string[] args)
            {
                var lastNames = File.ReadAllLines("yourtxtfile.txt").OrderBy(line => line.Split(',')[1]);    
            }