c# - C# 中的数组搜索

标签 c# arrays search

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

希望大家能帮忙。

( 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();
    }
})

最佳答案

如果你在 foreach 上交换嵌套循环,你可以使代码更具可读性和 IndexOf功能。代码如下:

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();

关于c# - C# 中的数组搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44083530/

相关文章:

c# - 如何在 Visual Studio 2015 中进行单元测试

c# - 哪个是在 ASP.NET(C#) 中使用字符串的最佳实践

c - 试图比较数组中的字符,但它永远不会捕获 C

facebook - 如何使用 Graph-API 在特定位置搜索 Facebook 的所有用户

ios - 将与搜索字符串匹配的字符串的一部分加粗

php - 搜索引擎的困境

c# - 我如何在 Xcode 中开发 C#?

c# - System.Array 到列表的转换

javascript - 在 Javascript 数组中使用 indexOf()

ios - 无法将类型 '__NSCFConstantString' 的值转换为 'NSArray'