[英]How can i sort my list of names alphabetically?
I would like to know, how can i sort the names and surenames alphabetically in my list.我想知道,如何按字母顺序对列表中的名称和确定名称进行排序。
I'm not sure, but i googled and i'm guessing it only sort's by the name.我不确定,但我用谷歌搜索,我猜它只是按名称排序。
public void FilterParticipants(List<string> players, PlayerContainer allPlayers)
{
for (int i = 0; i < allPlayers.Count; i++)
{
if (!players.Contains(allPlayers.FindName(i) + " " + allPlayers.FindSurname(i)))
{
players.Add(allPlayers.FindName(i) + " " + allPlayers.FindSurname(i));
}
}
players.Sort();
}
If you want to sort your player names by Surname and then Name and cannot change your design to have a List<Player>
passed in, then here's one solution.如果您想按姓氏然后按姓名对玩家姓名进行排序,并且无法更改设计以传入List<Player>
,那么这里有一个解决方案。
Note there's a slight design change, as it's usually better to return a new list rather than modifying the input list.请注意,设计略有变化,因为返回新列表通常比修改输入列表更好。 Also, the method name is a little misleading.此外,方法名称有点误导。 "Filter" implies that you're reducing the set of items based on some criteria, but in this case we're adding items if they don't exist, so I renamed it to GetCombinedParticipants
. “过滤器”意味着您正在根据某些条件减少项目集,但在这种情况下,我们将添加不存在的项目,因此我将其重命名为GetCombinedParticipants
。
Given that, here's one way you could implement it.鉴于此,这是您可以实现它的一种方法。 Note that this design uses Substring
to find the last space in the name, which is used as a delimeter between the first name and the last name (which therefore assumes that there are no spaces in the last name).请注意,此设计使用Substring
来查找姓名中的最后一个空格,该空格用作名字和姓氏之间的分隔符(因此假设姓氏中没有空格)。 If there are, then I don't know how you could possibly identify them from a List<string>
, which is another good reason to create a Player
class with separate FirstName
and Surname
poperties...如果有,那么我不知道您如何从List<string>
识别它们,这是创建具有单独FirstName
和Surname
属性的Player
类的另一个很好的理由...
public List<string> GetCombinedParticipants(List<string> players,
PlayerContainer allPlayers)
{
// Make a copy of the input list
var results = players.ToList();
for (int i = 0; i < allPlayers.Count; i++)
{
var fullName = $"{allPlayers.FindName(i)} {allPlayers.FindSurname(i)}";
if (!results.Contains(fullName)) results.Add(fullName);
}
// Order by last name, then by first name
return results
.OrderBy(name => name.Substring(name.LastIndexOf(" ") + 1))
.ThenBy(name => name.Substring(0, name.LastIndexOf(" ")))
.ToList();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.