我有以下课程的清单:

public class PostOrderDataModel
{
    public string OCN { get; set; }
    public string Quantity { get; set; }
    public string VerticalTypeName { get; set; }
    public Dictionary<string, string> VerticalTypeQuantity { get; set; }
}


具有相同OCN的多个实例:

List<PostOrderDataModel> lstPostOrderDataModel = new List<PostOrderDataModel>();

lstPostOrderDataModel[0] = new PostOrderDataModel { OCN = "AX", Quantity = "1", VerticalTypeName = "Internet", VerticalTypeQuantity = null} ;
lstPostOrderDataModel[1] = new PostOrderDataModel { OCN = "AX", Quantity = "2", VerticalTypeName = "Video", VerticalTypeQuantity = null};
lstPostOrderDataModel[2] = new PostOrderDataModel { OCN = "BX", Quantity = "2", VerticalTypeName = "Phone", VerticalTypeQuantity = null};


现在,我想创建一个PostOrderDataModel的新列表,并用OCN将分组的VerticalTypeName和填充为VerticalTypeName和key。我尝试过这种方法,但这样一来,我只能针对Key获得一项。如何访问这两个(VerticalTypeName,Quantity)项目并将其添加到我的词典value中?

var results = lstPostOrderDataModel.GroupBy(
    p => p.OCN,
    p => p.VerticalTypeName,
    (key, g) => new { OCN = key, VerticalTypeName = g.ToList() });


上面的代码仅针对每个OCN给出了VerticalTypeName。我也想要数量,因此可以在字典中添加。

最佳答案

元素选择器应为p => p而不是p => p.VerticalTypeName。完成后,您可以按以下步骤填充VerticalTypeQuantity

 var results = lstPostOrderDataModel.GroupBy(
                p => p.OCN,
                p => p,
                (key, g) => new {
                       OCN = key,
                      VerticalTypeQuantity = g.ToDictionary(e => e.VerticalTypeName,
                         e => e.Quantity)
                });

关于c# - 在LINQ中按列表分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53594726/

10-10 07:38