【问题标题】:Get the index of a partially matching item in a list c# using linq使用linq获取列表c#中部分匹配项的索引
【发布时间】:2015-11-25 13:12:41
【问题描述】:

我有字符串列表。如果列表包含该部分字符串,则找出该项目的索引。请查看代码以获取更多信息。

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");
}

【问题讨论】:

    标签: c# linq list indexof


    【解决方案1】:

    你可以使用List.FindIndex:

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

    【讨论】:

    • 如果该项目不在列表中,则会导致异常。有什么选择吗?
    • @SandeepKushwah:如果该项目不存在,则索引为-1,因此您只需检查一下即可。
    【解决方案2】:

    你可以用这个

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

    编辑

    如果使用List&lt;string&gt;,最好使用FindIndex。 但在我的辩护中,使用FindIndex 并没有按照 OP 的要求使用 LINQ ;-)

    编辑 2

    应该使用FirstOrDefault

    【讨论】:

    • 我正在寻找最简单的解决方案,因此接受了 Tims 的回答。感谢您的努力!
    【解决方案3】:

    这就是我在没有 Linq 的情况下使用它的方式,并想缩短它所以发布了这个问题。

    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");
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      • 2018-10-07
      • 2015-11-10
      • 1970-01-01
      相关资源
      最近更新 更多