简体   繁体   中英

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?

您可以使用List<T>.IndexOf方法。

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; }
}

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM