Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently return the first and last item in a SortedList<> in C#?

Tags:

c#

sortedlist

My question is like the following question but with SortedList<Tkey, TValue> instead of just the original SortedList.

Return first element in SortedList in C#

There doesn't seem to be a function like GetKey().

like image 527
Hyrial Avatar asked Oct 17 '25 04:10

Hyrial


1 Answers

You can simply use list.FirstOrDefault() and list.LastOrDefault().

These two methods will return default(KeyValuePair<TKey,TValue>) if the list is empty.

And it's better to use them because using list.First() and list.Last() will throw error in case the list was empty.

like image 120
Mohamad Mousheimish Avatar answered Oct 18 '25 18:10

Mohamad Mousheimish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!