IReadOnlyDictionary<TKey, TValue> Interface
public interface IReadOnlyDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>, ICollection<KeyValuePair<TKey, TValue>>
Represents a sorted collection of key and value pairs that are available to the user from the dictionary only. This interface provides no methods for adding or removing elements from the dictionary.
Type Parameters
TKey
- The type of keys in the dictionary.
TValue
- The type of values in the dictionary.
Properties
Count
{ get; }
- Gets the number of elements contained in the
IReadOnlyDictionary<TKey, TValue>
.
Item(TKey key)
{ get; }
- Gets the element with the specified key.
Methods
ContainsKey(TKey key)
(TKey key)
- Determines whether the
IReadOnlyDictionary<TKey, TValue>
contains an element with the specified key.
GetEnumerator()
()
- Returns an enumerator that iterates through the collection.
TryGetValue(TKey key, out TValue value)
(TKey key, out TValue value)
- Gets the element with the specified key.
Remarks
The IReadOnlyDictionary<TKey, TValue>
interface represents a collection of key/value pairs. It is designed to be used when you need to access a dictionary but do not intend to modify it.
Implementations of this interface should ensure that the key type TKey
is immutable or that any mutable aspects of the key do not affect its equality comparison or hash code.
Example Usage
using System;
using System.Collections.Generic;
public class Example
{
public static void Main(string[] args)
{
IReadOnlyDictionary<string, int> population = new Dictionary<string, int>
{
{ "Moscow", 12678079 },
{ "Saint Petersburg", 5384342 },
{ "Novosibirsk", 1625631 }
};
Console.WriteLine("Cities in the dictionary:");
foreach (KeyValuePair<string, int> pair in population)
{
Console.WriteLine($"- {pair.Key}: {pair.Value}");
}
string cityToFind = "Moscow";
if (population.ContainsKey(cityToFind))
{
Console.WriteLine($"\nPopulation of {cityToFind}: {population[cityToFind]}");
}
if (population.TryGetValue("Novosibirsk", out int populationCount))
{
Console.WriteLine($"Population of Novosibirsk is: {populationCount}");
}
}
}