C# ArrayList - Contains() 方法

C# ArrayList 的 Contains() 方法用于检查元素是否在 ArrayList 中。

此方法执行线性搜索操作,复杂度为 O(n),其中 n 表示元素数量。

语法

以下是 C# ArrayList 的 Contains() 方法的语法 -

public virtual bool Contains (object? item);

参数

此方法接受一个元素(对象)作为参数,用于在 ArrayList 中进行搜索。该值可以为 null。

返回值

如果在 ArrayList 中找到该元素,则此方法返回 true;否则返回 false。

示例 1:在 ArrayList 中使用 Contains() 方法

以下是使用 Contains() 方法在 ArrayList 中定位元素的基本示例 -

    
using System;
using System.Collections;

class Program
{
   static void Main()
   {
      ArrayList arrayList = new ArrayList { "A", "B", "C", "D" };
      string find = "B";
      
      bool res = arrayList.Contains(find);
      Console.WriteLine($"Is there '{find}' available in the list? {res}");
   }
}

输出

以下是输出 -

Is there 'B' available in the list? True

示例 2:查找 ArrayList 中不同类型的元素

让我们看另一个使用 Contains 方法的示例,以检查 ArrayList 中是否存在某个元素 -

using System;
using System.Collections;
class Program
{
   static void Main()
   {
      // 创建具有混合数据类型的 ArrayList
      ArrayList arrayList = new ArrayList { 1, 2, 3, "Hello", "World", 4.5 };

      int numberToFind = 3;
      bool numberResult = arrayList.Contains(numberToFind);
      Console.WriteLine($"Does the ArrayList contain the number {numberToFind}? {numberResult}");

      string stringToFind = "World";
      bool stringResult = arrayList.Contains(stringToFind);
      Console.WriteLine($"Does the ArrayList contain the string '{stringToFind}'? {stringResult}");
   }
}

输出

以下是输出 -

Does the ArrayList contain the number 3? True
Does the ArrayList contain the string 'World'? True

示例 3:检查 ArrayList 中的人员

以下示例创建了一个自定义对象。在这里,我们使用 Contains() 方法检查 ArrayList 中是否存在人员详细信息 -

using System;
using System.Collections;

class Person {
   public string Name {
      get;
      set;
   }
   public int Age {
      get;
      set;
   }

   public override bool Equals(object obj) {
      if (obj is Person other) {
         return this.Name == other.Name && this.Age == other.Age;
      }
      return false;
   }
   public override int GetHashCode()
   {
      return HashCode.Combine(Name, Age);
   }
}

class Program {
   static void Main() {
      // 使用自定义对象创建 ArrayList
      ArrayList arrayList = new ArrayList {
         new Person {
            Name = "Aman", Age = 25
         },
         new Person {
            Name = "Akash", Age = 30
         }
      };

      // 检查对象
      Person personToFind = new Person {
         Name = "Aman", Age = 25
      };
      bool personResult = arrayList.Contains(personToFind);
      Console.WriteLine($"Does the ArrayList contain {personToFind.Name}, age {personToFind.Age}? {personResult}");

   }
}

输出

以下是输出 -

Does the ArrayList contain Aman, age 25? True

csharp_arraylist.html