我制作了一个程序,用户可以在其中以名字、中间名首字母(可选)和姓氏格式输入任意多个姓名。然后我拆分名称并将它们分配给名为 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/