gpt4 book ai didi

c# - 无法在 Linq 中获取外部组的 key

转载 作者:太空宇宙 更新时间:2023-11-03 10:50:29 24 4
gpt4 key购买 nike

我通过 Linq 创建了一个嵌套组。我根据学生姓名的第 0 个元素创建了第一组。第二组基于学生姓名。我无法获得外部组的键,即'h' 或 'a'。请帮助。

代码:

List<student> li = new List<practice.student>()
{
new student(){name="harry",marks=50},
new student(){name="harry",marks=60},
new student(){name="hermione",marks=50},
new student(){name="hermione",marks=60},
new student(){name="ajax",marks=60},
new student(){name="ajax",marks=70},
new student(){name="abby",marks=60},
new student(){name="abby",marks=70}
};

var query1 = li.GroupBy(t => t.name[0]).Select(t => t.GroupBy(s => s.name));

foreach (var item in query1)
{
Console.WriteLine(item.Select(t=>t.Key));

foreach (var item1 in item)
{
Console.WriteLine("Key:"+item1.Key);

foreach (var item2 in item1)
{
Console.WriteLine(item2.name+","+item2.marks);
}
Console.WriteLine();
}
Console.WriteLine();
}

输出:

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Linq.IGrouping`2[S
ystem.String,practice.student],System.String]
Key:harry
harry,50
harry,60

Key:hermione
hermione,50
hermione,60


System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Linq.IGrouping`2[S
ystem.String,practice.student],System.String]
Key:ajax
ajax,60
ajax,70

Key:abby
abby,60
abby,70

最佳答案

您可以使用匿名类型,例如:

var query1 = li.GroupBy(t => t.name[0]).Select(t => new {Letter=t.Key, Students=t.GroupBy(s => s.name)});

foreach (var item in query1)
{
Console.WriteLine(item.Letter);
foreach (var item1 in item.Students)
{
Console.WriteLine("Key:" + item1.Key);
foreach (var item2 in item1)
{
Console.WriteLine(item2.name+","+item2.marks);
}
Console.WriteLine();
}
Console.WriteLine();

}

或者,为了缩短您的代码,只需在 foreach 循环中使用 GroupBy:

foreach(var letter in li.GroupBy(l => l.name[0]).OrderBy(l => l.Key))
{
Console.WriteLine("Letter:" + letter.Key);
foreach (var student in letter.GroupBy(l => l.name).OrderBy(l => l.Key))
{
Console.WriteLine(String.Format("\n\tKey: {0}", student.Key));
foreach (var mark in student.OrderBy(s => s.marks))
Console.WriteLine(String.Format("\t\t{0}, {1}", mark.name, mark.marks));
}
Console.WriteLine();
}

输出:

Letter:a

Key: abby
abby, 60
abby, 70

Key: ajax
ajax, 60
ajax, 70

Letter:h

Key: harry
harry, 50
harry, 60

Key: hermione
hermione, 50
hermione, 60

关于c# - 无法在 Linq 中获取外部组的 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21601641/

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