Sandeep Kushwah
Sandeep Kushwah

Reputation: 592

Get the index of a partially matching item in a list c# using linq

I have List of string. If the list contains that partial string then find out the index of that item. Please have a look on code for more info.

List<string> s = new List<string>();
s.Add("abcdefg");
s.Add("hijklm");
s.Add("nopqrs");
s.Add("tuvwxyz");

if(s.Any( l => l.Contains("jkl") ))//check the partial string in the list
{
    Console.Write("matched");

    //here I want the index of the matched item.
    //if we found the item I want to get the index of that item.

}
else
{
    Console.Write("unmatched");
}

Upvotes: 1

Views: 2778

Answers (3)

Sandeep Kushwah
Sandeep Kushwah

Reputation: 592

This is how I was using it without Linq and wanted to shorten it so posted this question.

List<string> s = new List<string>();
s.Add("abcdefg");
s.Add("hijklm");
s.Add("nopqrs");
s.Add("tuvwxyz");
if(s.Any( l => l.Contains("tuv") ))
{
   Console.Write("macthed");
   int index= -1;
   //here starts my code to find the index
   foreach(string item in s)
   {
     if(item.IndexOf("tuv")>=0)
     {
       index = s.IndexOf(item);
       break;
     }

   }
   //here ends block of my code to find the index
   Console.Write(s[index]);
  }
  else
    Console.Write("unmacthed");
 }

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460068

You can use List.FindIndex:

int index = s.FindIndex(str => str.Contains("jkl"));  // 1
if(index >= 0)
{
   // at least one match, index is the first match
}

Upvotes: 5

Dbuggy
Dbuggy

Reputation: 911

you can use this

var index = s.Select((item,idx)=> new {idx, item }).Where(x=>x.item.Contains("jkl")).FirstOrDefault(x=>(int?)x.idx);

Edit

In case when using a List<string>, FindIndex is better to use. But in my defence, using FindIndex is not using LINQ as requested by OP ;-)

Edit 2

Should have used FirstOrDefault

Upvotes: 1

Related Questions