📌  相关文章
📜  C#|获取一个包含ListDictionary中的键的ICollection

📅  最后修改于: 2021-05-29 18:41:25             🧑  作者: Mango

ListDictionary.Keys属性用于获取包含ListDictionary中的键的ICollection。

句法:

public System.Collections.ICollection Keys { get; }

返回值:返回一个ICollection,其中包含ListDictionary中的键。

下面是说明ListDictionary.Keys属性的用法的程序:

范例1:

// C# code to get an ICollection
// containing the keys in the ListDictionary
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");
  
        // Get an ICollection containing
        // the keys in the ListDictionary
        ICollection ic = myDict.Keys;
  
        // Displaying the keys in ICollection ic
        foreach(String str in ic)
        {
            Console.WriteLine(str);
        }
    }
}
输出:
Australia
Belgium
Netherlands
China
Russia
India

范例2:

// C# code to get an ICollection
// containing the keys in the ListDictionary
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("I", "first");
        myDict.Add("II", "second");
        myDict.Add("III", "third");
        myDict.Add("IV", "fourth");
        myDict.Add("V", "fifth");
  
        // Get an ICollection containing
        // the keys in the ListDictionary
        ICollection ic = myDict.Keys;
  
        // Displaying the keys in ICollection ic
        foreach(String str in ic)
        {
            Console.WriteLine(str);
        }
    }
}
输出:
I
II
III
IV
V

笔记:

  • ICollection中值的顺序未指定,但与Values方法返回的ICollection中关联值的顺序相同。
  • 返回的ICollection不是静态副本。相反,ICollection会参考原始ListDictionary中的键。因此,对ListDictionary的更改将继续反映在ICollection中。
  • 检索此属性的值是O(1)操作。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.listdictionary.keys?view=netframework-4.7.2