gpt4 book ai didi

C# GroupBy - 创建多个分组级别

转载 作者:太空狗 更新时间:2023-10-29 20:54:43 26 4
gpt4 key购买 nike

给定以下类:

public class Transaction
{
public string Category { get; set; }
public string Form { get; set; }
}

如何获得一组按 CategoryForm 分组的交易?

基本上我希望它像这样输出:

Category 1
Form 1
Transaction1
Transaction2
Transaction3
...
Form 2
Transaction1
Transaction2
Transaction3
...
Category 2
Form 1
Transaction1
Transaction2
Transaction3
...
Form 2
Transaction1
Transaction2
Transaction3
...

最佳答案

这是一个使用嵌套 foreach 循环的示例,我不确定您如何在单个 linq 语句字符串中执行此操作,也许有很多 selectmanys?

var transactions = new[]{
new{Category = "1", Form = "1", Title = "Trans1" },
new{Category = "1", Form = "1", Title = "Trans2" },
new{Category = "1", Form = "1", Title = "Trans3" },
new{Category = "1", Form = "2", Title = "Trans1" },
new{Category = "1", Form = "2", Title = "Trans2" },
new{Category = "1", Form = "2", Title = "Trans3" },
new{Category = "2", Form = "1", Title = "Trans1" },
new{Category = "2", Form = "1", Title = "Trans2" },
new{Category = "2", Form = "1", Title = "Trans3" },
new{Category = "1", Form = "3", Title = "Trans1" },
new{Category = "1", Form = "3", Title = "Trans2" },
new{Category = "1", Form = "3", Title = "Trans3" },
};

foreach(var byCategory in transactions.GroupBy(x => x.Category))
{
Console.WriteLine(byCategory.Key);
foreach(var byForm in byCategory.GroupBy(x => x.Form))
{
Console.WriteLine("\t" + byForm.Key);
foreach(var trans in byForm)
{
Console.WriteLine("\t\t" + trans.Title);
}
}
}

只是因为我很好奇我想出以下内容会是什么样子,你不应该在生产代码中使用它,因为它很荒谬(如果你有这样的数据结构,它应该被分解成类似的东西Dictionary<CategoryName, FormGroup> 或有意义类型的东西)

Dictionary<string, Dictionary<string, List<string>>> tooManyDictionaries = transactions
.GroupBy(x => x.Category)
.ToDictionary(
catGroup => catGroup.Key,
catGroup => catGroup
.GroupBy(x => x.Form)
.ToDictionary(
formGroup => formGroup.Key,
formGroup => formGroup.Select(x => x.Title).ToList()));

关于C# GroupBy - 创建多个分组级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19042143/

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