开发者

Dictionary<int,string> Remove last item

开发者 https://www.devze.com 2023-03-13 11:27 出处:网络
Ok I\'m being dense. How do I remove the last item in a dictionary? I have code that checks for the number in the dictionary and ifs too many it always removes the last one to make room the for the

Ok I'm being dense.

How do I remove the last item in a dictionary?

I have code that checks for the number in the dictionary and ifs too many it always removes the last one to make room the for the next but I can't see a straightforward way to do it

开发者_C百科
if (recentDic.Count>= recentItemLimit )
  recentDic.RemoveAt(recentDic.Count-1)

recentDic.Add(i,someString);

UPDATE: Thanks for the comments, you learn something everyday. I have moved over to a OrderedDictionay and am now using RemoveAt


Dictionary doesn't keep any order of its elements and therefore there is no way to know what a last one means.

If you want to remove a random one you can do something like what @Richard said:

dict.Remove(dict.Keys.Last());

or

dict.Remove(dict.Keys.First());


As @fiver notes: there is no order to a Dictionary so "last item" doesn't really make sense.

However you can get something that looks like "last":

dict.Remove(dict.Keys.Last());


you could use

recentDic.Remove(d.Last().Key);


this?

var dictionary = new Dictionary<int, string>();
dictionary.Remove(dictionary /* .OrderBy(o => o.Value) */ .Last().Key);


But if you want to remove somekind of element based on some order, try using the SortedDictionary. Then you can remove the last key by using dict.Remove(dict.Keys.Last()), as noted by others.


If "last" is meant in a temporal way, you can keep a reference to the last inserted key and remove that one.


try this in your way

 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");

            }


For the benefit of future readers, some corrections to the above misinformation:

  1. The order of a dictionary is ALWAYS the order in which each item was added. It is a fallacy that there is no order to a dictionary. The order is not random, and is completely predictable.
  2. The order of a dictionary can be accessed and modified using Linq as Petar Ivanov explained above. If it does not work for you (like it did not work for Derf Skren) Ensure you add using System.Linq; in your using tags.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号