Group by List in LINQ

时间:2018-12-03 13:19:18

标签: c# linq group-by

I have a List of following class:

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; }
}

having multiple instances with same 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}; 

Now, I want to make a new list of PostOrderDataModel and fill the VerticalTypeQuantity dictionary with VerticalTypeName as key and Quantity as value, grouped by OCN. I tried this but this way i am only able to get one item against Key. How can I access both(VerticalTypeName,Quantity) items and add it to my dictionary VerticalTypeQuantity?

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

Above code gives me the VerticalTypeName only against each OCN. I want the Quantity too so I can add in my dictionary.

1 个答案:

答案 0 :(得分:3)

元素选择器应为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) 
                });