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

时间:2015-07-27 02:15:37

标签: c# arrays string contains

我正在使用此代码检查数组中是否存在字符串(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()函数的数组中的字符串。

3 个答案:

答案 0 :(得分:1)

如果可以有多个匹配项,那么请使用:

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

}

否则:

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

}

答案 1 :(得分:0)

你需要在Any方法中使用lambda表达式: https://code.msdn.microsoft.com/LINQ-Quantifiers-f00e7e3e#AnySimple

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

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

答案 2 :(得分:0)