Свойство Key
Свойство Key структуры
KeyValuePair<TKey, TValue>
возвращает компонент ключа пары. Свойство
только для чтения.
Синтаксис
TKey key = pair.Key;
Пример
Давайте прочитать Key из пары:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
KeyValuePair<int, string> pair = new KeyValuePair<int, string>(4, "d");
Console.WriteLine(pair.Key);
}
}
Результат выполнения кода:
4
Пример
Давайте собрать ключи из пар и отсортировать:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<int, string> map = new Dictionary<int, string>
{
{2, "b"},
{1, "a"}
};
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"
Пример
Давайте использовать Key в условии:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
KeyValuePair<string, int> pair = new KeyValuePair<string, int>("abcde", 1);
if (pair.Key == "abcde")
{
Console.WriteLine("yes");
}
}
}
Результат выполнения кода:
"yes"
Смотрите также
-
свойство
Value,
которое возвращает значение -
структура
KeyValuePair,
которая объединяет ключ и значение -
свойство
Keys,
которое собирает все ключи -
индексатор
Dictionary,
который принимает ключ