IndexOf List in a List

mynugget99

New member
Joined
Oct 14, 2025
Messages
1
Programming Experience
Beginner
Ok lets say I have a list in a list. Say list name is players and each player contains three more items. One for id, playername, and color.

players[0][0] = 1001
players[0][1] = Bob
players[0][2] = red

players[1][0] = 1002
players[1][1] = Joe
players[1][2] = yellow

players[2][0] = 1003
players[2][1] = Tom
players[2][2] = blue

players[3][0] = 1004
players[3][1] = Bill
players[3][2] = blue

Lets say I know the players id of 1003. How do I get the first list index of 1003 which would be 2?
 
That's a terrible data structure to begin with. What you should be doing is defining a type with three properties to represent a player and then creating a list of instances of that type. E.g.
C#:
Expand Collapse Copy
public class Player
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Color { get; set; }

    public Player(int id, string name, string color)
    {
        Id = id;
        Name = name;
        Color = color;
    }
}
C#:
Expand Collapse Copy
var players = new List<Player>
              {
                  new Player(1001, "Bob", "Red"),
                  new Player(1002, "Joe", "Yellow"),
                  new Player(1003, "Tom", "Blue"),
                  new Player(1004, "Bill", "Blue")
              };
You can then find the index of the desired item using the FindIndex method of the List:
C#:
Expand Collapse Copy
var player1003Index = players.FindIndex(p => p.Id == 1003);
If you insist on using the list of lists, which is what your grandfather might have done if he wrote code when he was your age, then you can still use that FindIndex method:
C#:
Expand Collapse Copy
var player1003Index = players.FindIndex(l => l[0] == 1003);
 
Last edited:
Note that, as the name suggests, FindIndex will find the index of the first matching item. If you want the item itself then don't find the index first and then get the item by index. Instead, call Find and it will return the item.
 
I wonder if our OP was loading data from a text file and using String.Split() to parse the fields, and then just throwing those fields straight into a list. My only doubt is that the OP would have had a list of arrays of strings, rather than a list of of list of strings.

C# is a strongly-typed language. Take advantage of it by using the appropriate data structures as noted by @jmcilhinney above. Don't be stringly-typed.
 
Back
Top Bottom