包括通過查找數組中某個元素的下標(第⼀次出現時的下標,最后⼀次出現時的下標),查找某個數組中是否有某元素。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace study1_repeat
{
class Program
{
static void Main(string[] args)
{
int[] intArr = { 1, 2, 3, 4, 5, 6, 3, 5, 3 };
int value1 = 3;
int value2 = 8;
int first1 = Array.IndexOf(intArr, value1);
//查找value1第⼀次出現的索引
int first2 = Array.IndexOf(intArr, value2);
int end1 = Array.LastIndexOf(intArr, value1);
int end2 = Array.LastIndexOf(intArr, value2);
//查找最后⼀次出現的索引
int result1 = Array.BinarySearch(intArr, value1);
int result2 = Array.BinarySearch(intArr, value2);
//查找value1第⼀次出現的索引,這個⽅法采⽤⼆分法搜索。
bool contain1;
bool contain2;
//定義兩個布爾值。
if (((System.Collections.IList)intArr).Contains(value1))
{
contain1 = true;
}
else {
contain1 = false;
}
if (((System.Collections.IList)intArr).Contains(value2)) {
contain2 = true;
}
else
{
contain2 = false;
}
//將結果輸出出來
Console.WriteLine("數組中的⼀個{0}的下標為:{1}", value1, first1);
Console.WriteLine("數組中的⼀個{0}的下標為:{1}", value2, first2);
Console.WriteLine("數組中的最后⼀個{0}的下標為:{1}", value1, end1);
Console.WriteLine("數組中的最后⼀個{0}的下標為:{1}", value2, end2);
Console.WriteLine("數組中{0}的下標為:{1}", value1, result1);
Console.WriteLine("數組中{0}的下標為:{1}", value2, result2);
if (contain1)
{
Console.WriteLine("數組中包含{0}", value1);
}
else {
Console.WriteLine("數組中不包含{0}", value1);
}
if (contain2)
{Console.WriteLine("數組中包含{0}", value2);
}
else
{
Console.WriteLine("數組中不包含{0}", value2);
}
Console.ReadLine();
}
}
}
Array.IndexOf(intArr, value1)、Array.LastIndexOf(intArr, value1)、Array.BinarySearch(intArr, value2)在找到相應的元素時
會返回找到的元素的下標,如果沒有找到的話,前兩者會返回-1,最后⼀種會返回⼀個負數。
Array的Constains⽅法(⽤來查找某個元素是否存在)是對IList中的⽅法的實現,所以在使⽤時要先將其轉換為IList對象,轉換格式
為((System.Collections.IList)intArr).Contains(元素)
其中(System.Collections.IList)intArr是將intArr強制轉化為IList類型,再外⾯的括號是為了將轉化后的作為⼀個整體調⽤constains
⽅法。
輸出效果

