Click here to Skip to main content
15,894,124 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi,

I'd like to get the 1st dictionary entry without a key. I know I can setup a foreach KeyValuePair loop and break out after the 1st iteration, but there must be a better way. Any ideas?

The reason I want to do this is the dictionary contains application names and corresponding rows on a spreadsheet. The items in the dictionary are added in row order. I need to get the 1st row number in order to add a heading right above it. The data loaded into the dictionary comes from a file and is different for each spreadsheet, however the same logic applies to all of them.

Thank you,
Posted
Updated 30-Jul-10 12:11pm
v2
Comments
William Winner 30-Jul-10 18:23pm    
The point that was being made is that even though you might add the items in the same logical way and in a specific order does not mean that the first element in the dictionary is the first one that was added. It's implemented as a hash table meaning that as you add a new entry it could get placed anywhere in the list.

It really sounds like you'd be better off using a List. Why did you choose the dictionary to begin with?
Toli Cuturicu 31-Jul-10 8:16am    
Reason for my vote of 2
First Dictionary Entry - there is no such thing; this concept does not exist.
gggustafson 4-May-14 14:21pm    
I think you are being overly harsh. The fact that there is no first dictionary entry in the Dictionary data structure does not mean there is no first dictionary entry. Most new programmers have no idea how the dictionary is implemented. But that's not stupid (what you are implying), rather that is inexperience. I believe that you should have shared your knowledge with OP and suggested ways in which he could have accomplished what he wanted.
gggustafson 4-May-14 14:24pm    
Since you appeart to have no interest in retrieving the entries by application name, why not use the row number as your key?

Why the first. In dictionary the key determines the values and it can be at any level. What is special about the first key. Can you use TryGetValue() which takes key as input. See here[^]
 
Share this answer
 
Comments
gggustafson 4-May-14 14:20pm    
You have not answered the question. This is not a solution, it is a comment.
You can use the First or FirstOrDefault extension methods:
C#
Dictionary<object, object> dict = new Dictionary<object, object>();
// dict.Add(new object(), new object()); // optional
object firstObj = dict.FirstOrDefault().Value;

but like Yusuf said, why? Dictionaries are unordered so they don't really have a concept of a "first" or "last" element.

IEnumerable.First[^]
IEnumerable.FirstOrDefault[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900