dictionary - KeyValuePair naming by ValueTuple in C# 7 -
can new feature in c# 7.0 (in vs 2017) give tuple fields names translated keyvaluepairs?
lets assume have this:
class entry { public string someproperty { get; set; } } var allentries = new dictionary<int, list<entry>>(); // adding keys lists of entry
it nice like:
foreach ((int collectionid, list<entry> entries) in allentries)
i have added system.valuetuple
project.
being able write better traditional style:
foreach (var kvp in allentries) { int collectionid = kvp.key; list<entry> entries = kvp.value; }
deconstruction requires deconstruct
method defined either on type itself, or extension method. keyvaluepaire<k,v>
doesn't have deconstruct
method, need define extension method:
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; } }
this allows write:
var allentries = new dictionary<int, list<entry>>(); foreach(var (key, entries) in allentries) { ... }
for example:
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}"); } }
Comments
Post a Comment