【问题标题】:Array Search in C#C# 中的数组搜索
【发布时间】:2017-10-20 09:06:51
【问题描述】:

我正在尝试搜索一个数组以找到另一个较小的数组值。我使用了嵌套循环,找到的值完美显示。但是,我还想打印未找到的值,谁能帮我改进我的代码,以便在循环中打印未找到的值,而不像我在代码中那样使用文字(代码块//改进代码)

希望任何人都可以提供帮助。

( class Program  
{
    static void Main(string[] args)
    {
        int[] intArray = { 5, 12, 0, 67, 75, 3, 27, 1, 98};
        int[] searchValues = { 0, 25, 99, 12, 3 };
        for (int i = 0; i < searchValues.Length; ++i)
        {
            for (int j = 0; j< intArray.Length; ++j)
            { 
                if (searchValues[i]== intArray[j])
                {
                    Console.WriteLine("The Value {0} Has been found in index {1} of intarray ", searchValues[i], j);
                }               
            }
            // improve the code
            if (i == 1 || i == 2)
            {
                Console.WriteLine("The Value {0} was Not found in intarray ", searchValues[i]);
            }
        }
        Console.Read();
    }
})

【问题讨论】:

    标签: c# arrays search


    【解决方案1】:

    使另一个临时数组与具有相同值的搜索数组相同,而是与搜索数组匹配,然后与临时数组匹配,然后当您的 if 语句为真并且您显示匹配的值时,使用 int_max 更新您的临时数组的值。毕竟工作显示临时数组的值不等于int_max。现在将显示不匹配的值。这是最简单的一个。

    【讨论】:

    • 你能添加一些源代码来备份你的理论吗?
    【解决方案2】:

    如果您在 foreachIndexOf 函数上交换嵌套循环,您可以使代码更具可读性。代码如下所示:

    int[] intArray = { 5, 12, 0, 67, 75, 3, 27, 1, 98 };
    int[] searchValues = { 0, 25, 99, 12, 3 };
    
    
    foreach (var arr in searchValues)
    {
         int index = Array.IndexOf(intArray, arr);
         if (index != -1)
               Console.WriteLine("The Value {0} Has been found in index {1} of intarray ", arr, index);
         else
               Console.WriteLine("The Value {0} was Not found in intarray ", arr);
     }
    
    Console.ReadKey();
    

    【讨论】:

      【解决方案3】:

      使用 LINQ 的更短的解决方案:

      searchValues.ToList().Where(val => intArray.Contains(val)).ToList().ForEach(val => Console.WriteLine(string.Format("Index of {0}:\t {1}", val, Array.IndexOf(intArray, val))));
      searchValues.ToList().Where(val => !intArray.Contains(val)).ToList().ForEach(val => Console.WriteLine(string.Format("Index of {0}:\t {1}", val, "None")));
      

      输出:

      int[] intArray = { 5, 12, 0, 67, 75, 3, 27, 1, 98 };
      int[] searchValues = { 0, 25, 99, 12, 3 };
      

      0 的索引:2

      12 的索引:1

      3 的索引:5

      25 的索引:无

      99 指数:无

      或者如果您不介意打印顺序:

      searchValues.ToList().Select(val => new KeyValuePair<int, int>(val, Array.IndexOf(intArray, val))).ToList().ForEach(kvp => Console.WriteLine(string.Format("Index of {0}:\t {1}", kvp.Key, (kvp.Value == -1 ? "None" : kvp.Value.ToString()))));
      

      0 的索引:2

      25 的索引:无

      99 指数:无

      12 的索引:1

      3 的索引:5

      【讨论】:

        【解决方案4】:
        ( class Program  
        {
            static void Main(string[] args)
            {
                int[] intArray = { 5, 12, 0, 67, 75, 3, 27, 1, 98};
                int[] searchValues = { 0, 25, 99, 12, 3 };
        
                foreach (int item in searchValues)
                   if (Array.IndexOf(intArray, item)!= -1)
                       Console.Writeline("Item exists in list: ",item)
                   else Console.Writeline("Item does not exist in list: ",item)
        
                Console.Read();
            }
        })
        

        【讨论】:

        • 如果您也对索引感兴趣,可以重写代码(但您只提到了值)
        • intArray.FindIndex(s => s.Contains(item)) //(获取索引)
        • 您已经在使用IndexOf,无需同时引入FindIndex
        • 现在他可以在以后需要时将找到的元素的索引保存在变量中(而不是只检查它是否为-1)
        【解决方案5】:

        最简单的方法是将索引存储在一个变量中,然后在内部for循环结束后检查它的值:

        for (int i = 0; i < searchValues.Length; ++i)
        {
            int idx = -1;
        
            for (int j = 0; j< intArray.Length; ++j)
            { 
                if (searchValues[i] == intArray[j])
                {
                    idx = j;
                    break;
                }               
            }
            // improve the code
            if (idx >= 0)
            {
                Console.WriteLine("The Value {0} Has been found in index {1} of intarray ", searchValues[i], idx);
            }
            else
            {
                Console.WriteLine("The Value {0} was Not found in intarray ", searchValues[i]);
            }
        }
        

        另一种方法是使用 LINQ:

        int[] intArray = { 5, 12, 0, 67, 75, 3, 27, 1, 98};
        int[] searchValues = { 0, 25, 99, 12, 3 };
        
        var indices = searchValues.Select(i => new { Value = i, Index = Array.IndexOf(intArray, i) });
        var foundValues = indices.Where(x => x.Index >= 0).ToArray();
        var unfoundValues = indices.Where(x => x.Index < 0).ToArray();
        
        foreach (var val in foundValues)
            Console.WriteLine("The Value {0} Has been found in index {1} of intarray ", val.Value, val.Index);
        
        foreach (var val in unfoundValues)
            Console.WriteLine("The Value {0} was Not found in intarray ", val.Value);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-06-04
          • 1970-01-01
          • 2016-03-08
          • 2013-12-26
          • 2012-03-19
          • 1970-01-01
          相关资源
          最近更新 更多