¿Se puede traducir la nueva característica en C# 7.0 (en VS 2017) para dar nombres de campos de tupla a KeyValuePairs?
Supongamos que tengo esto:
class Entry { public string SomeProperty { get; set; } } var allEntries = new Dictionary<int, List<Entry>>(); // adding some keys with some lists of EntrySería bueno hacer algo como:
foreach ((int collectionId, List<Entry> entries) in allEntries) Ya he agregado System.ValueTuple al proyecto.
Poder escribirlo así sería mucho mejor que este estilo tradicional:
foreach (var kvp in allEntries) { int collectionId = kvp.Key; List<Entry> entries = kvp.Value; }La deconstrucción requiere un método Deconstruct definido en el tipo mismo o como un método de extensión. KeyValuePaire<K,V> en sí mismo no tiene un método Deconstruct , por lo que debe definir un método de extensión:
static class MyExtensions { public static void Deconstruct<K,V>(this KeyValuePair<K,V> kvp, out K key, out V value) { key=kvp.Key; value=kvp.Value; } }Esto le permite escribir:
var allEntries = new Dictionary<int, List<Entry>>(); foreach(var (key, entries) in allEntries) { ... }Por ejemplo:
var allEntries = new Dictionary<int, List<Entry>>{ [5]=new List<Entry>{ new Entry{SomeProperty="sdf"}, new Entry{SomeProperty="sdasdf"} }, [11]=new List<Entry>{ new Entry{SomeProperty="sdfasd"}, new Entry{SomeProperty="sdasdfasdf"} }, }; foreach(var (key, entries) in allEntries) { Console.WriteLine(key); foreach(var entry in entries) { Console.WriteLine($"\t{entry.SomeProperty}"); } }