SoFunction
Updated on 2025-04-16

How to get Key value based on index value in dictionary in C#

C# dictionary gets the Key value based on the index value

Get Key and Value values ​​according to dictionary index

var key = ("Index Value").Key;
var value= ("Index Value").Value;

Get the random start time of a sequence and set the corresponding end time

Dictionary<string, string> dic = new Dictionary<string, string>();
("06:00", "07:30");
("08:00", "11:30");
("12:00", "14:00");
("14:30", "17:00");
("16:00", "21:00");
("17:00", "21:00");
("19:00", "21:00");

/// <summary>
/// Get the start and end time/// </summary>
private void GetTime(out DateTime dtStart, out DateTime dtEnd)
{
    var strKey= ((())).Key;
    var strValue = dic[strKey];
    dtStart = (strKey);
    dtEnd = (strValue);
}

C# dictionary finds the corresponding key based on the value

In C#, the LINQ extension method can be used to find the corresponding key based on the value of the dictionary.

The following code can be used:

Dictionary<string, int> dict = new Dictionary<string, int>()
{
    {"apple", 1},
    {"banana", 2},
    {"orange", 3},
};
string key = (x =>  == 2).Key;
(key);

This outputs "banana" because it is a key with a value of 2.

Note that this method only returns the key of the first match found in the dictionary. If there are multiple keys with the same value, only the first key found is returned.

If no match is found, the default value is returned (null in the example).

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.