Структура KeyValuePair
Структура KeyValuePair<TKey, TValue>
из System.Collections.Generic представляет
одну пару ключ и значение. Её возвращает
перечисление Dictionary<TKey, TValue>
и принимают перегрузки
Add
и Remove.
Синтаксис
KeyValuePair<TKey, TValue> pair = new KeyValuePair<TKey, TValue>(key, value);
Пример
Давайте создать пару и вывести поля:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
KeyValuePair<int, string> pair = new KeyValuePair<int, string>(2, "b");
Console.WriteLine(pair.Key);
Console.WriteLine(pair.Value);
}
}
Результат выполнения кода:
2
"b"
Пример
Давайте собрать ключи из пар в отсортированный вывод:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<int, string> map = new Dictionary<int, string>
{
{3, "c"},
{1, "a"},
{2, "b"}
};
List<int> keys = new List<int>();
foreach (KeyValuePair<int, string> pair in map)
{
keys.Add(pair.Key);
}
keys.Sort();
Console.WriteLine(string.Join(" ", keys));
}
}
Результат выполнения кода:
"1 2 3"
Пример
Давайте сравнить две пары с одинаковым ключом:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
KeyValuePair<int, string> p1 = new KeyValuePair<int, string>(1, "a");
KeyValuePair<int, string> p2 = new KeyValuePair<int, string>(1, "a");
Console.WriteLine(p1.Key == p2.Key);
}
}
Результат выполнения кода:
True
Смотрите также
-
свойство
Key,
которое возвращает ключ -
свойство
Value,
которое возвращает значение -
метод
Add,
который принимает KeyValuePair -
класс
Dictionary,
который хранит множество пар