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

Get index in array if string exists in it using C#

我正在使用此代码来检查字符串 (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() 函数获取在数组中找到的字符串。

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

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