【问题标题】:Get index in array if string exists in it using C#如果字符串存在于数组中,则使用 C# 获取数组中的索引
【发布时间】:2015-10-17 02:28:40
【问题描述】:

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

【问题讨论】:

  • 使用IndexOf方法。
  • 什么是代码变量?你能给我们更多关于这里发生的事情的背景吗?但是,我确实尝试在下面回答。
  • 没错,我会编辑...代码变量是我要搜索数组的字符串。

标签: c# arrays string contains


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    否则:

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

    【讨论】:

    • String.IsNullOrEmpty() 可能比只检查空值更安全。这就是我将如何解决这个问题。很好的答案。
    • 他的问题是他想要索引。两种解决方案都没有给出索引。
    • @dman2306 “我想获取在数组中找到的字符串”。哪里提到了索引?
    • @rob the title "使用c#获取字符串数组中的索引"
    • @dman2306 很公平 - 但在这种情况下,问题的主体与标题相矛盾
    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      • 2020-09-19
      相关资源
      最近更新 更多