c# - 如何同步三个arrayLists的排序

标签 c#

我制作了一个程序,用户可以在其中以名字、中间名首字母(可选)和姓氏格式输入任意多个姓名。然后我拆分名称并将它们分配给名为 firstName、middleInitial 和 lastName 的字符串变量。由于可能有多个名称输入,我已将每个变量添加到其自己的名为 fName、mI 和 lName 的数组列表中。现在我必须对它们进行排序,以便它们按姓氏升序排列。这就是问题所在。对姓氏进行排序很容易,但是如何让 mI 和 fName arrayLists 以与 lName arrayList 相同的顺序排序?这是我的代码:

static void Main(string[] args)
{
    ArrayList fName = new ArrayList();
    ArrayList mI = new ArrayList();
    ArrayList lName = new ArrayList();


    Console.WriteLine("Please enter name: " + "(type quit to exit)");
    string inValue = Console.ReadLine(); //prime Readline

    while (inValue != "quit")
    {
        string firstName = "",
               middleInitial = "",
               lastName = "";


        string[] name = inValue.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        firstName = name[0];
        fName.Add(firstName);

        if (name.Length > 2)
        {
            middleInitial = name[1];
            mI.Add(middleInitial);

        }
        else
        {
            middleInitial = string.Empty;
            mI.Add(middleInitial);
        }
        if (name.Length == 2)
        {
            lastName = name[1];
            lName.Add(lastName);
        }
        else
        {
            lastName = string.Join(" ", name.Skip(2));
            lName.Add(lastName);
        }
        Console.WriteLine("Please enter name: " + "(type quit to exit)");
        inValue = Console.ReadLine();
    }
}

最佳答案

使用单个列表而不是 3 个。为此,您需要一个数据结构,将名字、中间名和姓氏封装到一个类中。

public class Name
{
  public string First { get; set; }
  public string Middle { get; set; }
  public string Last { get; set; }
}

而不是使用 ArrayList使用List<T>反而。接下来使用 LINQ 为您进行排序。

var list = new List<Name>();
list.Add(new Name { First = "Brian",   Middle = "D", Last = "Gideon" });
list.Add(new Name { First = "Bart",    Middle = "",  Last = "Simpson" });
list.Add(new Name { First = "Captain", Middle = "",  Last = "America" });
var ordered = list.OrderBy(x => x.Last).ThenBy(x => x.First).ThenBy(x => x.Middle);
foreach (Name item in ordered)
{
  Console.WriteLine(item.Last + ", " + item.First + " " + item.Middle);
}

关于c# - 如何同步三个arrayLists的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9425076/

相关文章:

c# - DataLoadOptions 等同于 LINQ to Entities?

c# - 如何在标签文本中显示计数?

c# - REST API(ASP.NET Web API 2)最佳实践: How to return 1 - N items that are not one type but 3 related types?

c# - 如何从随机池中选择一个号码,然后让号码不能重新选择

c# - 帮我解决架构问题

c# - 将聚合逆向工程为简单的 for 循环

c# - .Single(), .SingleOrDefault() 方法的实际使用

c# - MediaCapture + CaptureElement 生命周期/导航管理

c# - .Net Identity 中 UserManager 的奇怪行为

c# - Activator.CreateInstance(t, 42, args) 找不到构造函数