如果字符串存在,使用c#在数组中获取索引

本文关键字:数组 获取 索引 字符串 存在 使用 如果 | 更新日期: 2023-09-27 18:04:42

我使用这段代码来检查字符串(oCode/originalCode)是否存在于数组中(字符串由用户编写):

if (dic.cs.Any(code.Contains)) //dic.cs is in another class (cs is the array), the code variable is what I look for in the array
{
   //I want to get the string was found in the array with the "Contains" function
}

我想用Contains()函数获得在数组中找到的字符串。

如果字符串存在,使用c#在数组中获取索引

如果可能有多个匹配,则使用:

var foundCodes = dic.cs.Where(code.Contains);
foreach(var foundCode in foundCodes)
{
}
否则

:

var foundCode = dic.cs.FirstOrDefault(code.Contains);
if (!String.IsNullOrEmpty(foundCode))
{ 
}

Any方法中需要一个lambda表达式:https://code.msdn.microsoft.com/LINQ-Quantifiers-f00e7e3e AnySimple

var answer = yourArray.any(a => a == "WhatYouAreLookingFor");

如果答案是真的,那么你就找到了。

我相信你需要的是数组IndexOf方法。https://msdn.microsoft.com/en-us/library/system.array.indexof (v = vs.110) . aspx

相关文章: