Can the new feature in C# 7.0 (in VS 2017) to give tuple fields names be translated to KeyValuePairs?
Lets assume I have this:
class Entry
{
public string SomeProperty { get; set; }
}
var allEntries = new Dictionary<int, List<Entry>>();
// adding some keys with some lists of Entry
It would be nice to do something like:
foreach ((int collectionId, List<Entry> entries) in allEntries)
I have already added System.ValueTuple
to the project.
Being able to write it like that would be much better than this traditional style:
foreach (var kvp in allEntries)
{
int collectionId = kvp.Key;
List<Entry> entries = kvp.Value;
}
Dictionaries have a method called items that returns a sequence of tuples, where each tuple is a key-value pair. As you should expect from a dictionary, the items are in no particular order. The dictionary method update also takes a list of tuples and adds them, as key-value pairs, to an existing dictionary.
The KeyValuePair class stores a pair of values in a single list with C#. Set KeyValuePair and add elements − var myList = new List<KeyValuePair<string, int>>(); // adding elements myList.
The KeyValuePair is a struct, and it is a generic type.
KeyValuePair<TKey,TValue> is used in place of DictionaryEntry because it is generified. The advantage of using a KeyValuePair<TKey,TValue> is that we can give the compiler more information about what is in our dictionary. To expand on Chris' example (in which we have two dictionaries containing <string, int> pairs).
Deconstruction requires a Deconstruct
method defined either on the type itself, or as an extension method. KeyValuePaire<K,V>
itself doesn't have a Deconstruct
method, so you need to define an 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 you to 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}");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With