ListDictionary.Contains(Object)方法用于检查ListDictionary是否包含特定键。
句法:
public bool Contains (object key);
在这里, key是要在ListDictionary中定位的键。
返回值:如果ListDictionary包含具有指定键的条目,则该方法返回true ,否则返回false 。
异常:如果键为null,则此方法将提供ArgumentNullException。
下面给出了一些示例,以更好地理解实现:
范例1:
// C# code to check if ListDictionary
// contains a specific key
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
// Driver code
public static void Main()
{
// Creating a ListDictionary named myDict
ListDictionary myDict = new ListDictionary();
myDict.Add("Australia", "Canberra");
myDict.Add("Belgium", "Brussels");
myDict.Add("Netherlands", "Amsterdam");
myDict.Add("China", "Beijing");
myDict.Add("Russia", "Moscow");
myDict.Add("India", "New Delhi");
// Checking if ListDictionary contains
// the key "Brazil"
Console.WriteLine(myDict.Contains("Brazil"));
}
}
输出:
False
范例2:
// C# code to check if ListDictionary
// contains a specific key
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
// Driver code
public static void Main()
{
// Creating a ListDictionary named myDict
ListDictionary myDict = new ListDictionary();
myDict.Add("Australia", "Canberra");
myDict.Add("Belgium", "Brussels");
myDict.Add("Netherlands", "Amsterdam");
myDict.Add("China", "Beijing");
myDict.Add("Russia", "Moscow");
myDict.Add("India", "New Delhi");
// Checking if ListDictionary contains
// the key "null". This should raise
// "ArgumentNullException" as the key is null
Console.WriteLine(myDict.Contains(null));
}
}
运行时错误:
Unhandled Exception:
System.ArgumentNullException: Key cannot be null.
Parameter name: key
注意:此方法是O(n)运算,其中n是Count。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.listdictionary.contains?view=netframework-4.7.2