get fist element from dictionary in C#

Posted on 2007-10-15
Last Modified: 2012-05-05
Hi! Is there a simple way to return the first element from Dictionary. I'm trying to do it the following way but it doesn't work:

            Dictionary<string, bool> temp = new Dictionary<string,bool>();
            temp.Add("Z", false);
            temp.Add("T", false);
            temp.Add("A", false);
            temp.Add("D", false);

            string t = temp.GetEnumerator().Current.Key;

I need to get t="Z" from the dictionary, but i get t equal to null

Thank you
Question by:izloch2
    LVL 96

    Accepted Solution

    Try this:

                Dictionary<string, bool> temp = new Dictionary<string, bool>();
                temp.Add("Z", true);
                temp.Add("T", false);
                temp.Add("A", false);
                temp.Add("D", false);

                string t = "";
                foreach (string key in temp.Keys)
                    t = key;

    LVL 22

    Expert Comment

    The order in which keys and values are returned is not the necessarily same order used for the inserts.

    Dictionary<string, bool>.KeyCollection keys = temp.Keys;

    Now you can search the key collection for "Z".


    Featured Post

    Do You Know the 4 Main Threat Actor Types?

    Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

    Join & Write a Comment

    Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
    This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
    This video discusses moving either the default database or any database to a new volume.
    Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

    734 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    24 Experts available now in Live!

    Get 1:1 Help Now