gpt4 book ai didi

c# - 将嵌套键值对分组到字典

转载 作者:太空宇宙 更新时间:2023-11-03 22:18:46 25 4
gpt4 key购买 nike

我有以下代码:

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

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

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

我该怎么做。 ??

最佳答案

您可以使用 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 |   \_ Name1 |   \_ Name2 \_ 2     \_ Name3     \_ Name42 \_ 3     \_ Name5     \_ Name6     \_ Name63 \_ 4     \_ Name7

Nested dictionaries are often not very nice to use, though.I'd probably prefer a simple lookup table:

var result = list
.ToLookup(
x => Tuple.Create(x.Key, x.Value.Key),
x => x.Value.Value);

关于c# - 将嵌套键值对分组到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3978531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com