1

I have string list like,

list[0]="want"
list[1]="to"
list[2]="create"
list[3]="user"
list[4]="account"

I need to take the "user" string's index value. i.e, 3. I tried this way,

list.Where(o => o.Contains("user")).ToList();

I know it won't return the index position. How can I achieve this? Anyhelp?

Raj De Inno
  • 1,092
  • 2
  • 14
  • 33

1 Answers1

10

If you need to get the index of an existing string that you know completely use:

int index = list.IndexOf("user");

If the string only contains "user" but may be a bigger string that you don't have:

int index = list.FindIndex(item => item.Contains("user"));

In both cases, if index is 0 or greater you have the index and a negative value signals that the item was not found.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
  • This is good, but I just want to point out that if you use the `FindIndex` version, if there is more than one element that contains "user", it will return the index of the first element only. It's hard to tell from the question/example whether that would be a problem or not. – Elezar Jan 22 '16 at 07:05
  • Same with `IndexOf`. – Lasse V. Karlsen Jan 22 '16 at 13:34