Get first element from a dictionary in C#
To get first element from dictionary in C# we can directly useFirst()
method, this method will return the first element with Key
, Value
properties. Remember to include required namespaces:
using System.Collections.Generic;
, using System.Linq;
Example
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var myDict = new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" }
};
var firstElement = myDict.First();
string firstKey = firstElement.Key;
string firstKeyValue = firstElement.Value;
Console.WriteLine(firstKey);
Console.WriteLine(firstKeyValue);
}
}
Output
key1
value1
value1