[英]Dictionary<int,string> Remove last item
好吧,我很密集。
如何刪除字典中的最后一項?
我有代碼檢查字典中的數字,如果太多,它總是刪除最后一個,為下一個騰出空間,但我看不到一種直接的方法來做到這一點
if (recentDic.Count>= recentItemLimit )
recentDic.RemoveAt(recentDic.Count-1)
recentDic.Add(i,someString);
更新:感謝您的評論,您每天都會學到一些東西。 我已經轉移到 OrderedDictionay,現在正在使用 RemoveAt
Dictionary 不保留其元素的任何順序,因此無法知道最后一個是什么意思。
如果你想刪除一個隨機的,你可以像@Richard 所說的那樣做:
dict.Remove(dict.Keys.Last());
或者
dict.Remove(dict.Keys.First());
正如@fiver 指出的那樣:字典沒有順序,所以“最后一項”沒有意義。
但是,您可以獲得看起來像“最后”的東西:
dict.Remove(dict.Keys.Last());
你可以用
recentDic.Remove(d.Last().Key);
這個?
var dictionary = new Dictionary<int, string>();
dictionary.Remove(dictionary /* .OrderBy(o => o.Value) */ .Last().Key);
但是,如果您想根據某種順序刪除某種元素,請嘗試使用SortedDictionary 。 然后你可以使用dict.Remove(dict.Keys.Last())
刪除最后一個鍵,正如其他人所指出的那樣。
用你的方式試試這個
Dictionary<int, string> recentDic=new Dictionary<int,string>();
recentDic.Add(1,"vijay");
recentDic.Add(2,"ajay");
if (recentDic.Count >= 2)
{
int last = recentDic.Keys.Last();
recentDic.Remove(last);
recentDic.Add(last, "rahul");
}
如果“last”是暫時的,您可以保留對最后插入的鍵的引用並刪除該鍵。
為了將來讀者的利益,對上述錯誤信息進行一些更正:
Petar Ivanov
。 如果它對您不起作用(就像它對 Derf Skren 不起作用)確保您using System.Linq;
添加using System.Linq;
在您的using
標簽中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.