CSharp - Làm thế nào để tìm vị trí của một giá trị trong mảng dựa vào một giá trị cho trước? (How to find index of int array in CSharp from a given value?)


Trong bài này chúng ta sẽ tìm hiểu cách sử dụng Array.IndexOf() để xác định vị trí của một giá trị số trong một mảng số, với phương thức này thì ta không cần sử dụng tới vòng lâp for.





Array.IndexOf()

Là một method của lớp Array được sử dụng để xác định vị trí(index) của một giá trị trong một mảng, nếu tìm thấy thì sẽ trả về vị trí index của giá trị đó trong mảng, còn không tìm thấy thì sẽ trả về giá trị là -1.


Cú pháp - Syntax

Array.IndexOf(Name_Array, Value_Search);


Ví dụ - Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HowToFindIndexInArray
{
    class Program
    {
        static void Main(string[] args)
        {

            int[] iArray = { 55, 77, 210, 55 };

            //Using length property of an array to determine its length.
            Console.WriteLine("Number of elements in array: " + iArray.Length);
            Console.WriteLine("-------------------------------");

            int index;

            index = Array.IndexOf(iArray, 55);
            Console.WriteLine("Index of 55 in array is " + index);

            index = Array.IndexOf(iArray, 77);
            Console.WriteLine("Index of 77 in array is " + index);
           
            index = Array.LastIndexOf(iArray, 55);
            Console.WriteLine("Index of 55 from last is " + index);

            index = Array.LastIndexOf(iArray, 99);
            Console.WriteLine("Index of 55 from last is " + index);

            Console.WriteLine("\n\n\t -- VNLIVES.NET --");
            Console.ReadLine();

        }
    }
}


Kết quả - Result

















No comments:

Post a Comment