将嵌套的 KeyValue 对分组到 Dictionary

Roc*_*ngh 2 c# generics dictionary key-value

我有以下代码:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;


public class Test
{
    static void Main()
    {

        var list = new List<KeyValuePair<int, KeyValuePair<int, User>>>
                        {
                            new KeyValuePair<int, KeyValuePair<int, User>>(1,new KeyValuePair<int, User>(1,new User {FirstName = "Name1"})),
                            new KeyValuePair<int, KeyValuePair<int, User>>(1,new KeyValuePair<int, User>(1,new User {FirstName = "Name2"})),
                            new KeyValuePair<int, KeyValuePair<int, User>>(1,new KeyValuePair<int, User>(2,new User {FirstName = "Name3"})),
                            new KeyValuePair<int, KeyValuePair<int, User>>(1,new KeyValuePair<int, User>(2,new User {FirstName = "Name4"})),
                            new KeyValuePair<int, KeyValuePair<int, User>>(2,new KeyValuePair<int, User>(3,new User {FirstName = "Name5"})),
                            new KeyValuePair<int, KeyValuePair<int, User>>(2,new KeyValuePair<int, User>(3,new User {FirstName = "Name6"})),
                            new KeyValuePair<int, KeyValuePair<int, User>>(2,new KeyValuePair<int, User>(3,new User {FirstName = "Name6"})),
                            new KeyValuePair<int, KeyValuePair<int, User>>(3,new KeyValuePair<int, User>(4,new User {FirstName = "Name7"})),
                        };
    }
}
public class User
{
    public string FirstName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

上面你可以看到第一个 KeyValue Pair 的同一个键有多个值,进一步(在第二个嵌套键 Value Pair 中)有多个相同的键现在我想对它们进行分组并将列表对象转换为字典,其中键将在相同(如上所示的 1,2)但第一个值将是字典,第二个值将是集合。像这样:

var outputNeeded = new Dictionary<int,Dictionary<int,Collection<User>>>();
Run Code Online (Sandbox Code Playgroud)

我该怎么做。??

dtb*_*dtb 5

您可以使用 LINQ:

var result = list
    .GroupBy(
        x => x.Key,
        x => x.Value)
    .ToDictionary(
        g => g.Key,
        g => g.GroupBy(
                  y => y.Key,
                  y => y.Value)
              .ToDictionary(
                  h => h.Key,
                  h => new Collection<User>(h.ToList())));
Run Code Online (Sandbox Code Playgroud)

这将创建以下层次结构:

1
 \_ 1
 | \_ 姓名 1
 | \_ 姓名 2
 \_ 2
     \_ 姓名 3
     \_ 名称 4
2
 \_ 3
     \_姓名5
     \_ 姓名 6
     \_ 姓名 6
3
 \_ 4
     \_ 姓名7

但是,嵌套字典通常不太好用。我可能更喜欢简单的查找表:

var result = list
    .ToLookup(
        x => Tuple.Create(x.Key, x.Value.Key),
        x => x.Value.Value);
Run Code Online (Sandbox Code Playgroud)