Get the last element in a dictionary?

What do you mean by Last? Do you mean Last value added?

The Dictionary<TKey,TValue> class is an unordered collection. Adding and removing items can change what is considered to be the first and last element. Hence there is no way to get the Last element added.

There is an ordered dictionary class available in the form of SortedDictionary<TKey,TValue>. But this will be ordered based on comparison of the keys and not the order in which values were added.

EDIT

Several people have mentioned using the following LINQ style approach

var last = dictionary.Values.Last();

Be very wary about using this method. It will return the last value in the Values collection. This may or may not be the last value you added to the Dictionary. It’s probably as likely to not be as it is to be.

Leave a Comment