【问题标题】:Couldnt iterate all value in array with specific condition?无法在特定条件下迭代数组中的所有值?
【发布时间】:2019-11-25 16:16:42
【问题描述】:

我必须使用 for 循环来迭代一个数组以找到其中包含特定单词并将其添加到列表框中

String[] result= ["vicky","vinay@","google@","hello"];


for (l=0 ; l<= result.length; l++)
{
    if(result[l].contains("@"))
    {
         Listbox.Items.Add(result[l]);
    }
}

这是做什么的,它只获得第一个找到的值我没有获得第二个值?

【问题讨论】:

  • 您的代码中应该有异常。循环条件“l
  • 是的,我发现我的工作已经完成了,谢谢伙计

标签: c# asp.net asp.net-webpages


【解决方案1】:

在这里(但在我看来,在这种情况下使用 linq 将是一个更清洁的解决方案):

        String[] result = { "vicky", "vinay@", "google@", "hello" };
        List<string> StringsResult = new List<string>();

        for(int l = 0 ; l <= result.Length-1; l++)
        {
            if(result[l].Contains("@"))
            {
                StringsResult.Add(result[l]);
            }
        }

        foreach(String s in StringsResult)
        {
            System.Diagnostics.Debug.Write($"{s} ");
        }

输出:“vinay@”,“google@”

【讨论】:

    【解决方案2】:

    你可以用 Linq 简单地做到这一点:

    Listbox.Items.AddRange(result.Where(x => x.Contains("@")).ToList());
    

    但是,如果您只想使用 for 循环来完成:

    for(int i=0; i<result.Length;i++)
        if(result[i].Contains("@")) Listbox.Items.Add(result[i]);
    

    或者

    foreach(var item in result)
        if(item.Contains("@")) Listbox.Items.Add(item);
    

    【讨论】:

      【解决方案3】:

      它对我来说工作正常,没有错误

      String[] result = { "vicky", "vinay@", "google@", "hello" };
      
                  var Listbox = new List<string>();
                  for (int l = 0; l <= result.Length; l++)
                  {
                      if (result[l].Contains("@"))
                      {
                          Listbox.Add(result[l]);
                      }
                  }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-03
        • 1970-01-01
        • 2016-01-21
        • 1970-01-01
        • 2022-11-23
        • 2020-05-01
        • 2022-01-18
        • 1970-01-01
        相关资源
        最近更新 更多