C# 7 中 ValueTuple 的 KeyValuePair 命名

KeyValuePair naming by ValueTuple in C# 7

C# 7.0(在 VS 2017 中)的新功能是否可以将元组字段名称转换为 KeyValuePairs?

假设我有这个:

class Entry
{
  public string SomeProperty { get; set; }
}

var allEntries = new Dictionary<int, List<Entry>>();
// adding some keys with some lists of Entry

做这样的事情会很好:

foreach ((int collectionId, List<Entry> entries) in allEntries)

我已经将 System.ValueTuple 添加到项目中。

能这么写比传统的写法好很多:

foreach (var kvp in allEntries)
{
  int collectionId = kvp.Key;
  List<Entry> entries = kvp.Value;
}

解构需要一个 Deconstruct 方法定义在类型本身上,或者作为扩展方法。 KeyValuePaire<K,V>本身没有Deconstruct方法,所以需要定义一个扩展方法:

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

这允许你写:

var allEntries = new Dictionary<int, List<Entry>>();
foreach(var (key, entries) in allEntries)
{
    ...
}

例如:

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