0

I'm working on a project where I need to find the index of an item in my C# List and and the following 3 indexes.

For example:

I want to find the index of 'Mary' in my name List:

Joseph Mary John Peter Andrew

After I find the index of Mary I want to add the following 3 indexes (John, Peter, Andrew) and store them in an array.

  • 1
    Welcome to SO ! Did you make any try to find out, how we find the index of an item in a C# list? I am pretty sure that If you google it you would find millions of results. Thanks – Christos Jul 15 '17 at 16:27

2 Answers2

1

You can use the indexOf method on List<T> to find the index of the first matching item:

var items = new List<string> { "Joseph", "Mary", "John", "Peter", "Andrew" };

var indexOfMary = items.IndexOf("Mary");

var itemAtIndexOfMary = items[indexOfMary];

Once you've done that you can then index into the list (the last line of code) at any point to retrieve the item at that position.

Rob
  • 45,296
  • 24
  • 122
  • 150
0

int index = myList.IndexOf("Mary");

SteppingRazor
  • 1,222
  • 1
  • 9
  • 25
  • 1
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Donald Duck Jul 15 '17 at 18:17