简体   繁体   中英

KeyValuePair naming by ValueTuple in C# 7

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;
}

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}");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM