I have the following declaration:
Dictionary<string, Dictionary<string, string>> like = new Dictionary<string, Dictionary<string, string>>();
I need to get the first element out, but do not know the key or value. What’s the best way to do this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Note that to call
Firsthere is actually to call a Linq extension of IEnumerable, which is implemented byDictionary<TKey,TValue>. But for a Dictionary, “first” doesn’t have a defined meaning. According to this answer, the last item added ends up being the “First” (in other words, it behaves like a Stack), but that is implementation specific, it’s not the guaranteed behavior. In other words, to assume you’re going to get any defined item by calling First would be to beg for trouble — using it should be treated as akin to getting a random item from the Dictionary, as noted by Bobson below. However, sometimes this is useful, as you just need any item from the Dictionary.Just use the Linq
First():Note that using
Firston a dictionary gives you aKeyValuePair, in this caseKeyValuePair<string, Dictionary<string,string>>.Note also that you could derive a specific meaning from the use of
Firstby combining it with the LinqOrderBy: