Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary<TKey, TValue>.ForEach method

Tags:

c#

I wanna declare new extension method which similar to List.ForEach Method.

What I wanna archive:

var dict = new Dictionary<string, string>()
{
   { "K1", "V1" },
   { "K2", "V2" },
   { "K3", "V3" },
};


dict.ForEach((x, y) => 
{
   Console.WriteLine($"(Key: {x}, value: {y})");
});

How can I do that?

like image 519
Tân Avatar asked Feb 08 '23 05:02

Tân


1 Answers

You can write an extension method easily:

public static class LinqExtensions
{
    public static void ForEach<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, Action<TKey, TValue> invoke)
    {
        foreach(var kvp in dictionary)
            invoke(kvp.Key, kvp.Value);
    }
}

Using like this:

dict.ForEach((x, y) => 
{
   Console.WriteLine($"(Key: {x}, value: {y})");
});

Produces

Key: K1, value: V1
Key: K2, value: V2
Key: K3, value: V3
like image 96
Rob Avatar answered Feb 15 '23 10:02

Rob