-1

I have a list List<string> strList where strings are added to the list throughout the program.

I want to be able to find a certain position or index of the list containing a certain string.

I've managed to check if a string that contains a certain text exists using this code:

if (strList.Exists(str => str.Contains("Chicken")))
            {
                Console.WriteLine("Found it");
            }

But I would like to find which position in the list this string has.

Mr Riksson
  • 560
  • 3
  • 10
  • 29
  • 1
    Possible duplicate of [How to get the index of an item in a list in a single step?](http://stackoverflow.com/questions/17995706/how-to-get-the-index-of-an-item-in-a-list-in-a-single-step) – Stephen Byrne Feb 26 '17 at 14:56

2 Answers2

2

You can use FindIndex

 int index = strList.FindIndex(str => str.Contains("Chicken"));

Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire List.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Muhammad Saqlain
  • 2,112
  • 4
  • 33
  • 48
0

Muhammad solution is working fine with me , i just needed to avoid case issues ,i used the below ,same code with minor change

 int Index = listOfStrings.FindIndex(x => x.Msg.Equals(msg, StringComparison.OrdinalIgnoreCase));
Ali
  • 1,080
  • 16
  • 22