获取在字典中的最后一个元素? [英] Get the last element in a dictionary?

查看:191
本文介绍了获取在字典中的最后一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字典:

Dictionary<double, string> dic = new Dictionary<double, string>();

我怎样才能返回的最后一个元素在我的字典?

How can I return the last element in my dictionary?

推荐答案

你说的最后是什么意思?你的意思是最后加入的价值?

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

词典&LT; TKEY的,TValue&GT; 类是一个无序的集合。添加和删​​除项目可以改变了被认为是第一个和最后一个元件。因此,没有办法让最后一个元素添加。

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.

有一个在 SortedDictionary&LT的形式提供一个有序字典类; TKEY的,TValue&GT; 。但基于密钥,而不是在值的添加顺序进行比较,这将订购。

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.

修改

有几个人用下面的LINQ风格的方法提到

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.

这篇关于获取在字典中的最后一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆