Get first key from Dictionary

后端 未结 5 1666
你的背包
你的背包 2020-12-24 10:34

I\'m using a System.Collections.Generic.Dictionary.

I want to return the first key from this dictionary. I tried dic.Keys[0]

5条回答
  •  梦谈多话
    2020-12-24 11:32

    Assuming you're using .NET 3.5:

    dic.Keys.First();
    

    Note that there's no guaranteed order in which key/value pairs will be iterated over in a dictionary. You may well find that in lots of cases you get out the first key that you put into the dictionaries - but you absolutely must not rely on that. As Skirwan says, there isn't really a notion of "first". Essentially the above will give you "a key from the dictionary" - that's about all that's guaranteed.

    (If you don't know whether the dictionary is empty or not, you could use FirstOrDefault.)

提交回复
热议问题