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.
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
.
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). 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...
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.