gpt4 book ai didi

c# - 在 Linq 中使用分组创建字典(字典)

转载 作者:行者123 更新时间:2023-11-30 19:29:08 25 4
gpt4 key购买 nike

我知道我可以用循环来做到这一点(事实上,我现在是,但我正在努力学习/提高我的 Linq 技能,我也希望它能提供更有效的解决方案。所以,这是我的场景:

假设我有以下 3 个列表(我只是在编一个类似的例子,请原谅我的愚蠢):

Dim lstTeachers as New List(of string)
Dim lstStudentsSex as New List(of string)
Dim lstStudentName as New List(of string)

例如,它们是这样的:

lstTeachers:     lstStudentsSex:     lstStudentName:
Teacher 1 Male Whatever Name 1
Teacher 2 Female Whatever Name 2
Teacher 1 Female Whatever Name 3
Teacher 1 Female Whatever Name 4
Teacher 2 Male Whatever Name 5
Teacher 3 Male Whatever Name 6
Teacher 3 Female Whatever Name 7
Teacher 1 Male Whatever Name 8
Teacher 1 Female Whatever Name 9
Teacher 2 Male Whatever Name 10

每个列表中的每个条目与具有相同索引的其他条目相匹配 - 基本上就像一个数据表,只是存储在单独的列表中。

现在,假设我想用以下值创建以下结构:

Dim dictTeacherSexName as New Dictionary(Of String, Dictionary(Of String, List(of String)))

Dict1_Key: Dict1_Value / Dict2_Key: Dict2_Value:
Teacher 1 Male Whatever Name 1
Whatever Name 8
Female Whatever Name 3
Whatever Name 4
Whatever Name 9
Teacher 2 ...

...我希望这能解释我想要完成的事情。

再一次,我知道这可能是一个愚蠢的想法,但我问这个是因为我想提高我的 Linq 技能 - 特别是 Group By 和多重选择仍然吸引我,所以请帮忙。

非常感谢!

最佳答案

这三个列表让事情变得有点困难,但并非不可能。您首先按照@fsimonazzi 的建议将列表压缩在一起,或者您的查询基于列表索引而不是列表条目本身。结果可能如下所示:

(C#)

var result = Enumerable
.Range(0, lstTeachers.Count)
.GroupBy(i => lstTeachers[i])
.ToDictionary(g => g.Key, g => g
.GroupBy(i => lstStudentsSex[i])
.ToDictionary(h => h.Key, h => h
.Select(i => lstStudentName[i])
.ToList()));

// result is Dictionary<string, Dictionary<string, List<string>>>

关于c# - 在 Linq 中使用分组创建字典(字典),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13198355/

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