Find the index of an element in an array using the Array.IndexOf function in C#

WBOY
Release: 2023-11-18 09:59:01
Original
1279 people have browsed it

Find the index of an element in an array using the Array.IndexOf function in C#

Use the Array.IndexOf function in C# to find the index of an element in the array

In a C# program, when we need to find the index of an element in the array When, you can use the Array.IndexOf function. The Array.IndexOf function finds the specified element within the specified array range and returns the index of its first occurrence. If the element is not found, -1 is returned.

The following is a sample code that demonstrates how to use the Array.IndexOf function to find the index of an element in an array:

using System;

class Program
{
    static void Main()
    {
        // 定义一个整型数组
        int[] numbers = { 2, 4, 6, 8, 10 };

        // 需要查找的元素
        int target = 6;

        // 使用Array.IndexOf函数查找目标元素的索引
        int index = Array.IndexOf(numbers, target);

        if (index != -1)
        {
            Console.WriteLine($"元素 {target} 在数组中的索引为 {index}。");
        }
        else
        {
            Console.WriteLine($"元素 {target} 未找到。");
        }
    }
}
Copy after login

In the above sample code, we first define an integer array numbers , and then defines a target element that needs to be found, target is 6. Next, we call the Array.IndexOf function, pass in the numbers array and the target element target, and assign the returned index to the index variable. Finally, the search result is judged based on the returned index. If the index is not equal to -1, the index of the target element in the array is output; otherwise, the unfound information is output.

The above is a sample code for using the Array.IndexOf function in C# to find the index of an element in an array.

To summarize, the Array.IndexOf function is a very convenient method in C#, through which we can easily find the index of an element in the array. Whether in a simple example scenario or in actual development, using this function can improve code execution efficiency, reduce development time, and improve development efficiency.

The above is the detailed content of Find the index of an element in an array using the Array.IndexOf function in C#. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!