System.Collections.Specialized.StringCollection.Contains 方法

方法描述

确定指定的字符串是否在 StringCollection 中。

语法定义(C# System.Collections.Specialized.StringCollection.Contains 方法 的用法)

public bool Contains(
	string value
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
value System-String 要在 StringCollection 中定位的字符串。该值可以为 null。
返回值 System.Boolean 如果在 StringCollection 中找到 value,则为 true;否则为 false。

提示和注释

Contains 方法可以在执行进一步操作前确认字符串的存在。

此方法通过调用 Object.Equals 确定相等性。 字符串比较区分大小写。

此方法执行线性搜索;因此,此方法的运算复杂度是 O(n),其中 n 是 Count。

从 .NET Framework 2.0 开始,此方法对 item 使用该集合对象的 Equals 和 CompareTo 方法来确定项是否存在。 在 .NET Framework 的较早版本中,这是通过对集合中的对象使用 item 参数的 Equals 和 CompareTo 方法来确定的。

System.Collections.Specialized.StringCollection.Contains 方法例子

下面的代码示例搜索 StringCollection 中的元素。

using System;
using System.Collections;
using System.Collections.Specialized;

public class SamplesStringCollection  {

   public static void Main()  {

      // Creates and initializes a new StringCollection.
      StringCollection myCol = new StringCollection();
      String[] myArr = new String[] { "RED", "orange", "yellow", "RED", "green", "blue", "RED", "indigo", "violet", "RED" };
      myCol.AddRange( myArr );

      Console.WriteLine( "Initial contents of the StringCollection:" );
      PrintValues( myCol );

      // Checks whether the collection contains "orange" and, if so, displays its index.
      if ( myCol.Contains( "orange" ) )
         Console.WriteLine( "The collection contains \"orange\" at index {0}.", myCol.IndexOf( "orange" ) );
      else
         Console.WriteLine( "The collection does not contain \"orange\"." );

   }

   public static void PrintValues( IEnumerable myCol )  {
      foreach ( Object obj in myCol )
         Console.WriteLine( "   {0}", obj );
      Console.WriteLine();
   }

}

/*
This code produces the following output.

Initial contents of the StringCollection:
   RED
   orange
   yellow
   RED
   green
   blue
   RED
   indigo
   violet
   RED

The collection contains "orange" at index 1.

*/

异常

异常 异常描述

命名空间

namespace: System.Collections.Specialized

程序集: System(在 System.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。