如何在 c# 中根据如下分组的产品类别显示我的回复
这是我在提供者类中的方法
This is my method in the provider class
public async Task<List<ProductSummary>> GetProductDetails(string pId, bool isSplitVersion)
{
var response = await dbAccess.GetProductDetailsReport(pId);
List<ProductSummary> ProdList = new List<ProductSummary>();
if (isSplitVersion)
{
var distinctProductCat = response.GroupBy(x => x.PRODUCT_CATEGORY);
foreach (var productCategory in distinctProductCat)
{
foreach (var item in productCategory)
{
ProdList.Add(item);
}
return productReportMapper.Map(ProdList);
}
}
return productReportMapper.Map(response);
}
当 isSplitVersion 为 true 时,产品按产品类别分组,并将分配给 distinctProductCat .(即 category1,category2,category3)我想显示我的响应如下.(响应必须由产品类别分隔)
when the isSplitVersion is true, products are grouped by the product category and will assign to distinctProductCat .(i.e category1,category2,category3)And I want to appear my response as below.(Response has to be separated by the product categories)
{
"Value": {
"category1": [
{
...
"Product Name": "ABC",
"Product Category": "category1"
...
}
],
"category2": [
{
...
"Product Name": "EFG",
"Product Category": "category2"
...
},
{
...
"Product Name": "XYZ",
"Product Category": "category2"
...
},
{
...
"Product Name": "SDF",
"Product Category": "category2"
...
}
],
"category3": [
{
...
"Product Name": "BNV",
"Product Category": "category3"
...
},
{
...
"Product Name": "DFG",
"Product Category": "category3"
...
}
]
},
"Formatters": [],
"ContentTypes": [],
"DeclaredType": null,
"StatusCode": 200
}
从我实施的方法来看,我没有得到预期的响应.我如何调整提供者类中的代码以获得上述响应.(目前我的响应中只得到类别 1.我没有得到类别 2 和 3)
From the method that I have implemented, I don't get the expected response. How Can I adjust my code in the provider class to get the response as above.(At present I get only category 1 in my reponse.I don't get category 2 and 3)
感谢任何帮助.
谢谢.
你的问题是你正在检查你的第一个 for 循环
(foreach (var productCategory in distinctProductCat)
) 仅一次,因为您在第一次运行后返回 - return productReportMapper.Map(ProdList);
Your problem is you are going over your first for loop
(foreach (var productCategory in distinctProductCat)
)only once, cause you are returning just after the first run here - return productReportMapper.Map(ProdList);
在我看来你需要 Dictionary
而不是 List
,我不确定 productReportMapper.Map()
内部会发生什么,如果您根本需要它,因为您没有添加它,但我认为您想做这样的事情:
It seems to me like you need Dictionary<string, List<ProductSummary>>
and not List<ProductSummary>
,
and I am not sure what happens inside productReportMapper.Map()
, and if you need it at all, cause you did not add it, but I think you want to do something like this:
...
if (isSplitVersion)
{
var distinctProductCat = response
.GroupBy(x => x.PRODUCT_CATEGORY)
.ToDictionary(x => x.Key, x => x.ToList());
return productReportMapper.Map(distinctProductCat);
}
...