Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Get an ICollection containing the keys in ListDictionary in C#
The ListDictionary class in C# provides a Keys property that returns an ICollection containing all the keys in the dictionary. This is useful when you need to iterate through or process only the keys without accessing their corresponding values.
Syntax
Following is the syntax to get the keys collection from a ListDictionary −
ICollection keys = listDictionary.Keys;
Return Value
The Keys property returns an ICollection object that contains all the keys from the ListDictionary. The keys are returned in the same order as they were added to the dictionary.
Using Keys Property with String Keys
The following example demonstrates how to retrieve and iterate through keys in a ListDictionary containing electronic devices −
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main(){
ListDictionary listDict = new ListDictionary();
listDict.Add("1", "Laptop");
listDict.Add("2", "Tablet");
listDict.Add("3", "Desktop");
listDict.Add("4", "Speaker");
listDict.Add("5", "Earphone");
listDict.Add("6", "Headphone");
ICollection col = listDict.Keys;
Console.WriteLine("Keys in the ListDictionary:");
foreach(String s in col){
Console.WriteLine(s);
}
}
}
The output of the above code is −
Keys in the ListDictionary: 1 2 3 4 5 6
Using Keys Property with Character Keys
Here's another example using single character keys with names −
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main(){
ListDictionary listDict = new ListDictionary();
listDict.Add("A", "Tom");
listDict.Add("B", "John");
listDict.Add("C", "Kevin");
listDict.Add("D", "Tim");
ICollection col = listDict.Keys;
Console.WriteLine("Available keys:");
foreach(String s in col){
Console.WriteLine("Key: " + s);
}
Console.WriteLine("\nTotal number of keys: " + col.Count);
}
}
The output of the above code is −
Available keys: Key: A Key: B Key: C Key: D Total number of keys: 4
Key Features
-
The
Keysproperty returns a live collection − changes to the ListDictionary are reflected in the keys collection. -
Keys are returned in the insertion order, maintaining the sequence in which they were added.
-
The returned
ICollectionis read-only − you cannot modify the keys through this collection. -
You can use the
Countproperty of the returned collection to get the number of keys.
Conclusion
The Keys property of ListDictionary provides an efficient way to access all keys as an ICollection. This is particularly useful for iteration, counting, or when you need to process keys independently of their values in your C# applications.
