C# 中按字母顺序排序列表

Haider Ali 2023年10月12日
  1. C# 中使用 Sort() 方法按字母顺序对列表进行排序
  2. C# 中使用 foreach 循环来打印按字母顺序排列的列表
C# 中按字母顺序排序列表

本指南展示了如何在 c# 中按字母顺序对单词进行排序。c# 中有一个内置函数,我们可以使用它对列表进行排序。

C# 中使用 Sort() 方法按字母顺序对列表进行排序

首先,using System.Collections.Generic;,这是你需要导入的库才能在 c# 中使用列表。我们需要使用 Sort() 对列表进行排序。

之后,我们需要使用比较器来比较两个字符串。例如,看一下下面的代码。

citizens.Sort((x, y) => string.Compare(x.Name, y.Name));

在上面的代码行中,citizens 是列表,我们比较公民的姓名以按字母顺序对公民列表进行排序。

C# 中使用 foreach 循环来打印按字母顺序排列的列表

using System;

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;  // library import to use list;

namespace list_sort {
  class Program {
    static void Main(string[] args) {
      List<Person> citizens = new List<Person>(5);  // Creating List Of Person having size 5;
                                                    // Adding Persons in List
      citizens.Add(new Person("Mark", "Zuker", "Silicon Valley United States", 50));
      citizens.Add(new Person("Bill ", "Gates", "Silicon Valley United States", 70));
      citizens.Add(new Person("Jeff", "Bezoz", "Silicon Valley United States", 40));
      citizens.Add(new Person("Elon", "Musk", "Silicon Valley United States", 20));
      citizens.Add(new Person("Antony", "Gates", "Silicon Valley United States", 30));

      Console.WriteLine(":::::::::::::::::::::::::::::::Before Sorting ::::::::::::::::::::::::");
      // Prinring The List Names...
      foreach (Person p in citizens) {  // Loop through List with foreach
        Console.WriteLine(p.Name);
      }
      Console.WriteLine(":::::::::::::::::::::::::::::::After Sorting :::::::::::::::::");
      // Problem #  Sort List of Citizens According to Citizen Names orderby-alphabetical-order
      citizens.Sort((x, y) => string.Compare(x.Name, y.Name));
      foreach (Person p in citizens)  // Prniting After alphabetical Sort.
      {                               // Loop through List with foreach
        Console.WriteLine(p.Name);
      }
      Console.ReadKey();  // to Stay On Screen.
    }
  }
  class Person {
    public String Name;
    public String LastName;
    public String Address;
    public int age;
    public Person(String Name, String LastName, String Address, int Age) {
      this.Name = Name;
      this.LastName = LastName;
      this.Address = Address;
      this.age = Age;
    }
  }
}

首先,我们创建了一个 citizen 列表,然后添加了姓名、地址和年龄。我们在排序列表之前打印它,然后在排序列表之后打印它。

输出:

:::::::::::::::::::::::::::::::Before Sorting ::::::::::::::::::::::::
Mark
Bill
Jeff
Elon
Antony
:::::::::::::::::::::::::::::::After Sorting :::::::::::::::::
Antony
Bill
Elon
Jeff
Mark
作者: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

相关文章 - Csharp List

相关文章 - Csharp Sort