gpt4 book ai didi

c#/linq 数据分组

转载 作者:行者123 更新时间:2023-11-30 22:31:39 30 4
gpt4 key购买 nike

我有一个类似这样的产品类:

class Product
{
public string Name;
public int Year;
public int Vendor;
public int Count;
}

数据输入类似

Name Year Vendor Count

'A' 1990 1 15

'A' 1990 2 20

'A' 1998 4 5

'B' 1995 1 15

'B' 1995 2 2

我想将数据转换成一个新的结构,比如

class NewStructure
{
public string Name;
public int Year;
Dictionary<int, int> Vendor_Count;
}

Dictionary字段用来存储{Vendor, Count}对,Name和Year这对会有一个对应的字典。结果会是

Name Year Vendor Count

'A' 1990 1 15

2 20

'A' 1998 4 5

'B' 1995 1 15

2 2

我尝试了以下 linq 查询

from input in inputList
group inputList by new { input.Name, input.Year }
into grouping
orderby grouping.Key.Name, grouping.Key.Year
select new
{
ProductName = grouping.Key.Name,
OriginYear = grouping.Key.Year,
Vendor_Count = grouping.
}

但我无法正确获取“Vendor_Count”。我想知道我该怎么办?

最佳答案

如果(名称、年份、供应商)的组合是唯一的,则使用此方法:

inputList.GroupBy(x => new { x.Name, x.Year })
.Select(x => new
{
ProductName = x.Key.Name,
OriginYear = x.Key.Year,
Vendor_Count = x.ToDictionary(y => y.Vendor
y => y.Count)
})
.OrderBy(x => x.ProductName).ThenBy(x => x.OriginYear);

如果它不是唯一的,则使用它:

inputList.GroupBy(x => new { x.Name, x.Year })
.Select(x => new
{
ProductName = x.Key.Name,
OriginYear = x.Key.Year,
Vendor_Count = x.GroupBy(y => y.Vendor)
.ToDictionary(y => y.Key,
y => y.Sum(z => z.Count))
})
.OrderBy(x => x.ProductName).ThenBy(x => x.OriginYear);

关于c#/linq 数据分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9127413/

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