1

I have a List, which contains.

1. This is house.
2. I am writing with pen.

Now I want to know that at what index the string contains house(1.) How to do that without for loop? Array.IndexOf will not work as it will not find element with same match

Proneet
  • 139
  • 2
  • 10
  • 1
    Matthew Watson just provided an [answer on another question](http://stackoverflow.com/a/18609672/1324033) that will do this – Sayse Sep 04 '13 at 09:26

7 Answers7

4

to find the first index:

var idx = myList.FindIndex(x => x.Contains("abc"));
Rex
  • 2,130
  • 11
  • 12
1
var indexes = Enumerable.Range(0, list.Length)
                        .Where(index => list[index].Contains("1."));
cuongle
  • 74,024
  • 28
  • 151
  • 206
1

An elegant way is to use FindIndex

List<String> exampleList = new List<String>();
exampleList.Add("This is a house.");
exampleList.Add("I am writing with pen");

int index = exampleList.FindIndex(x => x.Contains("house"));
Console.WriteLine(index); //0

index = exampleList.FindIndex(x => x.Contains("pen"));
Console.WriteLine(index); //1

FindIndex searches for an element that matches the conditions defined by a specified predicate, and returns the zero-based index of the first occurrence within the List or a portion of it.

Ofiris
  • 6,047
  • 6
  • 35
  • 58
1

Clean and simple

string[] data = { "This is house", "I am writing with pen." };
List<string> list = new List<string>(data);

int index = list.FindIndex(str => str.Contains("house"));
Collie
  • 718
  • 7
  • 6
0
string key = "house";
var result = yourlist.Select((x,y)=>new{ListIndex = y, ElementIndex = x.IndexOf(key)})
          .Where(x=>x.ElementIndex > -1)
          .ToList();

With this code you'll have as result a collection of an Anonymous type, with 2 properties: the first one with the index of the list, and the second one with the index inside the string

Save
  • 11,450
  • 1
  • 18
  • 23
0
int index = Array.FindIndex(list.ToArray(), i => i.Contains("house") );
vborutenko
  • 4,323
  • 5
  • 28
  • 48
0
myList.FindIndex(x => x.ToLower().Contains("house"))

That is the solution if you want to search in a case-insensitive manner.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175