Iterate a IDictionary/Dictionary Object

10,306

Solution 1

        foreach (var item in dict_Options)
        {
            string varName = item.Value.varName;
        }

This iterates through all the KeyValuePair<T, T> in your dictionary

Solution 2

Just to add an alternative to the great answers already posted, you could do:

dict_Options.Keys.ToList().ForEach(m => SomeFunc(m.Value.varName));

Solution 3

foreach(var name in dict_Options.Select(x => x.Value.varName))
{
    SomeFunc(name);
}
Share:
10,306
cdub
Author by

cdub

Updated on July 07, 2022

Comments

  • cdub
    cdub almost 2 years

    I have code where this is declared:

     public IDictionary<string, OPTIONS> dict_Options = new Dictionary<string, OPTIONS>();
    
     public class OPTIONS
     {
            public string subjectId = string.Empty;
            public string varNumber = string.Empty;
            public string varName = string.Empty;
     }
    

    What's the easiest way to iterate over all the varNames in my dictionary object? Is there like a foreach?

  • Emaborsa
    Emaborsa about 9 years
    ...How could m.Value return something if m is actually the Key? I would write dict_Options.Keys.ToList().ForEach(m => SomeFunc(dict_Options[m]));