What is the best way to iterate over a dictionary?

前端 未结 30 1672
我寻月下人不归
我寻月下人不归 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:59

    Just wanted to add my 2 cent, as the most answers relate to foreach-loop. Please, take a look at the following code:

    Dictionary myProductPrices = new Dictionary();
    
    //Add some entries to the dictionary
    
    myProductPrices.ToList().ForEach(kvP => 
    {
        kvP.Value *= 1.15;
        Console.Writeline(String.Format("Product '{0}' has a new price: {1} $", kvp.Key, kvP.Value));
    });
    

    Altought this adds a additional call of '.ToList()', there might be a slight performance-improvement (as pointed out here foreach vs someList.Foreach(){}), espacially when working with large Dictionaries and running in parallel is no option / won't have an effect at all.

    Also, please note that you wont be able to assign values to the 'Value' property inside a foreach-loop. On the other hand, you will be able to manipulate the 'Key' as well, possibly getting you into trouble at runtime.

    When you just want to "read" Keys and Values, you might also use IEnumerable.Select().

    var newProductPrices = myProductPrices.Select(kvp => new { Name = kvp.Key, Price = kvp.Value * 1.15 } );
    

提交回复
热议问题