C
C#2y ago
Matt

❔ Check if list contains object with a specific property/variable value

I have a list of Players where Player is a simple object with a Name and ID. I need to check to see if a player with a specific ID is on the player list. I know that I could use a dictionary to do this but if there is a way to keep the list, that would be ideal. Here's a rough outline of what I'm trying to achieve
class Player
{
public string Name;
public ushort Id;

public Player(string name, ushort id)
{
Name = name;
Id = id;
}
}

class PlayerHandler
{
public static List<Player> Players = new();

public static void GetPlayer(ushort id)
{
if(Players.Contains()) return Player
}
}
class Player
{
public string Name;
public ushort Id;

public Player(string name, ushort id)
{
Name = name;
Id = id;
}
}

class PlayerHandler
{
public static List<Player> Players = new();

public static void GetPlayer(ushort id)
{
if(Players.Contains()) return Player
}
}
8 Replies
Matt
MattOP2y ago
I also know that a foreach loop would achieve the desired result but it's long and ugly and if there's something simpler great. Otherwise I'll go with the foreach
mindhardt
mindhardt2y ago
if you are sure that player exists then
public Player GetPlayer(ushort id)
{
return Players.First(p => p.Id == id);
//it throws if player not found
}
public Player GetPlayer(ushort id)
{
return Players.First(p => p.Id == id);
//it throws if player not found
}
I mostly do this
public Player? GetPlayer(ushort id)
{
return Players.FirstOrDefault(p => p.Id == id);
//it returns null if player not found
}
public Player? GetPlayer(ushort id)
{
return Players.FirstOrDefault(p => p.Id == id);
//it returns null if player not found
}
Which utilists nullable reference types so it does not throw obviously method should not be void for this case
Thinker
Thinker2y ago
Alternatively if you want something slightly more efficient, a regular for loop would probably be the best
public static Player? GetPlayer(ushort id)
{
for (int i = 0; i < players.Count; i++)
{
var player = players[i];
if (player.Id == id) return player;
}

return null;
}
public static Player? GetPlayer(ushort id)
{
for (int i = 0; i < players.Count; i++)
{
var player = players[i];
if (player.Id == id) return player;
}

return null;
}
mindhardt
mindhardt2y ago
Plz /close
Omnissiah
Omnissiah2y ago
you could use a SortedList<ushort, string> and/or SortedList<string, ushort>
mindhardt
mindhardt2y ago
Or a dictionary, I sometimes do that
Omnissiah
Omnissiah2y ago
depends on performance and memory occupation for a small collection and fast creation/deallocation even a List<(string, ushort)>() could do have you tried writing only /close
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server