gpt4 book ai didi

c# - LINQ 分组到多个组

转载 作者:行者123 更新时间:2023-11-30 13:38:25 24 4
gpt4 key购买 nike

我有以下数据

IEnumerable<Tuple<T, List<U>>> Data;

或者也可以表示为

Dictionary<T, List<U>> GroupedA

给定一个 T 它可能属于一个或多个 U。我想要反转它以便我可以查找 U 并找到所有相关联的T在结构中

Dictionary<U, List<T>> GroupedB;

试图想出一个简洁的 LINQ 表达式来反转字典。

编辑

其实下面的正确答案说明我真正想要的是

ILookup<U, T>

而不是

Dictionary<U, List<T>>

最佳答案

//Populating data
Dictionary<int, List<string>> GroupedA = new Dictionary<int, List<string>>();

GroupedA.Add(1, new List<string>{"1","2","3"});
GroupedA.Add(2, new List<string>{"1","32","3","4"});
GroupedA.Add(3, new List<string>{"1","52","43","4"});


//Inverting data
ILookup<string, int> GroupedB =
GroupedA.SelectMany(pair => pair.Value.Select(val => new{pair.Key, val}))
.ToLookup(pair => pair.val, pair => pair.Key);



//Printing data
var pairs = GroupedB.Select(pair => string.Format("{0} : {1}", pair.Key, string.Join(",", pair)));

Console.WriteLine (string.Join(Environment.NewLine, pairs));

打印:

1 : 1,2,3 
2 : 1
3 : 1,2
32 : 2
4 : 2,3
52 : 3
43 : 3

关于c# - LINQ 分组到多个组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16786157/

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