The syntax for iterating over dictionaries, if you needed both the key and the value, has always been a little awkward in C#, being a specific case of the awkwardness of the tuple-like hacks prior to the real thing in C# 7. You either had to do this:
```C#
IDictionary
foreach (var entry in dict) {
string key = entry.Key;
Foo value = entry.Value;
// ...
}
or this:
```C#
IDictionary<string, Foo> dict = GetFoos();
foreach (string key in dict.Keys) {
Foo value = dict[key];
// ...
}
Now that native tuples are present, it would be a great boon if dictionary iterators could be overloaded to return them if requested, so you could do something like
```C#
IDictionary
foreach ((string key, Foo value) in dict) {
// ...
}
```
Is this feasible for future versions of C#? I realize that it would probably mean IDictionary<TKey, TVal> would have to implement multiple IEnumerable<T>s, which is considered a no-no, but I feel it would be very convenient, if it were done carefully and properly. Or perhaps KeyValuePair could have a Deconstructor, would that also allow this to work, so did PR #19126 make this possible?
You can define an extension Deconstruct method,
static class C {
static void M(Dictionary<string, Foo> dict) {
foreach (var (key, value) in dict) {}
}
static void Deconstruct<T, U>(this KeyValuePair<T, U> k, out T t, out U u) {
t = k.Key; u = k.Value;
}
}
The KeyValuePair<TKey, TValue>.Deconstruct method is available in .NET Core 2.0 as well.
The extension method in #19126 is my favorite use of Deconstruct to date. 馃槃
@alex-slover The .NET Core version of this is dotnet/corefx#13746. The .NET Framework version is internal "Bug 292574", which I'm trying to get a status update on just so you can know.
For now I'm going to close this as External since it's being tracked already for both use cases.
@alex-slover I heard back, and there is no specific time frame for if or when .NET Standard or .NET Framework will be getting that method. Best bet for now is the extension method 馃憤
@sharwell
.Net Core 2.0 is released.. but no news about .Net Framework update... a bit frustrating... Please let us know about any news...
Most helpful comment
@sharwell
.Net Core 2.0 is released.. but no news about .Net Framework update... a bit frustrating... Please let us know about any news...