locked
How can i extract certain values from a dictionary ? RRS feed

  • Question

  • User1253338400 posted

    Hi 

    I have a dictionary with the following values:

    Dictionary<string, string> myDict = new Dictionary<string, string>();
    myDict.Add("FirstName", "Name");
    myDict.Add("LasatName", "Name");
    myDict.Add("MiddleName", "Name");
    myDict.Add("Street", "Address");
    myDict.Add("Suburb", "Address");
    myDict.Add("City", "Address");

    How can i extract only the value of the Key such that the value is Name.

    So for example I want to extract FirstName, LastName , MiddleName so that I have something like 

    string.format ( FIRST = "FirstName", MIDDLE="MiddleName",LAST="LastName", ??????)

    How can i get those values , firstname, lastname and  middle name via a linq expression 

    thanks

    Monday, August 19, 2019 6:46 AM

Answers

  • User665608656 posted

    Hi robby,

    If you want to get the key in the dictionary, I suggest you should get the key based on the value.

    Here is the code:

                Dictionary<string, string> myDict = new Dictionary<string, string>();
                myDict.Add("FirstName", "Name");
                myDict.Add("LasatName", "Name");
                myDict.Add("MiddleName", "Name");
                myDict.Add("Street", "Address");
                myDict.Add("Suburb", "Address");
                myDict.Add("City", "Address");
                var keys = myDict.Where(x => x.Value == "Name" || x.Value == "Address").Select(x => x.Key).ToList();

    You can refer to this link: LINQ: Getting Keys for a given list of Values from Dictionary and vice versa

    Here is the result :

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 20, 2019 2:52 AM

All replies