Deconstruction in foreach over dictionary

Is it possible in C # 7 to use deconstruction in foreach-loop over a dictionary? Something like that:

var dic = new Dictionary<string, int>{ ["Bob"] = 32, ["Alice"] = 17 }; foreach (var (name, age) in dic) { Console.WriteLine($"{name} is {age} years old."); } 

It does not work with Visual Studio 2017 RC4 and .NET Framework 4.6.2:

error CS1061: "KeyValuePair" does not contain a definition for "Deconstruct", and the extension method "Deconstruct" cannot be found that accepts the first argument of the type "KeyValuePair" (do you miss the using directive or assembly references?)

+16
source share
3 answers

First you need to add an extension method for KeyValuePair :

 public static void Deconstruct<T1, T2>(this KeyValuePair<T1, T2> tuple, out T1 key, out T2 value) { key = tuple.Key; value = tuple.Value; } 

Then you will get another error:

error CS8179: the predefined type 'System.ValueTuple`2' is not defined or not imported

According to this answer you need to install the NuGet System.ValueTuple package.

Then it should compile. However, Visual Studio 2017 RC4 will say that it cannot resolve symbol names name and age . They should hope to fix this in a future update.

+23
source

If you don't like writing the Deconstruct method, especially if you need it in only one place, here's how to do it as a single line with LINQ:

Using your original dictionary:

 var dic = new Dictionary<string, int>{ ["Bob"] = 32, ["Alice"] = 17 }; 

You can do it like this:

 foreach (var (name, age) in dic.Select(x => (x.Key, x.Value))) { Console.WriteLine($"{name} is {age} years old."); } 
+12
source

Deconstruct KeyValuePair<TKey,TValue> implemented in .NET Core 2.0 , but, unfortunately, not in the .NET Framework (preview before 4.8).

0
source

Source: https://habr.com/ru/post/1264925/


All Articles