What is the best way to iterate over a dictionary?

前端 未结 30 2230
我寻月下人不归
我寻月下人不归 2020-11-22 05:18

I\'ve seen a few different ways to iterate over a dictionary in C#. Is there a standard way?

30条回答
  •  眼角桃花
    2020-11-22 05:53

    Depends on whether you're after the keys or the values...

    From the MSDN Dictionary(TKey, TValue) Class description:

    // When you use foreach to enumerate dictionary elements,
    // the elements are retrieved as KeyValuePair objects.
    Console.WriteLine();
    foreach( KeyValuePair kvp in openWith )
    {
        Console.WriteLine("Key = {0}, Value = {1}", 
            kvp.Key, kvp.Value);
    }
    
    // To get the values alone, use the Values property.
    Dictionary.ValueCollection valueColl =
        openWith.Values;
    
    // The elements of the ValueCollection are strongly typed
    // with the type that was specified for dictionary values.
    Console.WriteLine();
    foreach( string s in valueColl )
    {
        Console.WriteLine("Value = {0}", s);
    }
    
    // To get the keys alone, use the Keys property.
    Dictionary.KeyCollection keyColl =
        openWith.Keys;
    
    // The elements of the KeyCollection are strongly typed
    // with the type that was specified for dictionary keys.
    Console.WriteLine();
    foreach( string s in keyColl )
    {
        Console.WriteLine("Key = {0}", s);
    }
    

提交回复
热议问题