'How to find where an object is located in a list?
i have a list "players" and i want to find if my player is
players[0]
or
players[1]
or whaterver. How do i do this?
Solution 1:[1]
There's a List<T>.IndexOf
method that you can use.
Solution 2:[2]
use of linq command
List<Player> players = new List<Player>();
players.Add(new Player() { Id = "1", Name = "angle" });
players.Add(new Player() { Id = "2", Name = "cristin" });
players.Add(new Player() { Id = "2", Name = "robert" });
var finded= players.Where(x => x.Name == "cristin").FirstOrDefault();
public class Player
{
public string Id { get; set; }
public string Name { get; set; }
}
Solution 3:[3]
How about this:
public int GetIndex(List<PlayerClass> playersList, PlayerClass player)
{
return playersList.FindIndex(a => a == player);
}
It should return -1 if the player is not in the list.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | CesarGon |
Solution 2 | Ali Feraidoony |
Solution 3 | Armin |