【问题标题】:Grouping Nested KeyValue pairs to Dictionary将嵌套键值对分组到字典
【发布时间】:2011-04-28 01:41:56
【问题描述】:

我有以下代码:

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

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

var outputNeeded = new Dictionary<int,Dictionary<int,Collection<User>>>();

我该怎么做。 ??

【问题讨论】:

  • 不清楚你想输出什么。请解释清楚一点

标签: c# generics dictionary key-value


【解决方案1】:

您可以使用 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())));

这将创建以下层次结构:

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

【讨论】:

  • 您好 dtb,非常感谢您的回复!我需要的最后一部分是集合而不是 List 。你能建议怎么做吗?
  • @Rocky Singh:只需将列表包装在 Collection 中。
猜你喜欢
  • 2011-04-28
  • 2019-02-14
  • 1970-01-01
  • 2021-10-20
  • 2021-12-27
  • 1970-01-01
  • 2016-02-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多