Huma Ali
Huma Ali

Reputation: 1809

Group by List in LINQ

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.

Upvotes: 1

Views: 70

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56393

The element selector should be p => p instead of p => p.VerticalTypeName. once done, you can then populate the VerticalTypeQuantity as follows:

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

Upvotes: 3

Related Questions