LCJ
LCJ

Reputation: 22662

Best LINQ way to create dictionary from list of custom entities

I have a list of DeleteByVendor objects.. It has two business entities – vendor and pricepage .. One pricepage can have multiple vendors.. And one vendor can be present in multiple pricepages.

We need to create a dictionary that will have each pricepage and the number of (distinct) vendors present in that pricepage. One pricepage should be present only once in that dictionary.

How can we do it using LINQ chain method approach?

Note: For "P3" the count should be 1 (though there is a duplicate record)

class Program
{
    static void Main(string[] args)
    {

        List<DeleteByVendor> vendorsForPages = new List<DeleteByVendor>();

        DeleteByVendor item1 = new DeleteByVendor() { VendorID = "V1", VendorName = "Vendor1", PricePage = "P1", Description = "Description1" };
        DeleteByVendor item2 = new DeleteByVendor() { VendorID = "V2", VendorName = "Vendor2", PricePage = "P1", Description = "Description1" };
        DeleteByVendor item3 = new DeleteByVendor() { VendorID = "V1", VendorName = "Vendor1", PricePage = "P2", Description = "Description2" };
        DeleteByVendor item4 = new DeleteByVendor() { VendorID = "V1", VendorName = "Vendor1", PricePage = "P3", Description = "Description3" };
        //Duplicate
        DeleteByVendor item5 = new DeleteByVendor() { VendorID = "V1", VendorName = "Vendor1", PricePage = "P3", Description = "Description3" };

        Dictionary<string, int> costPageVendorsCount = new Dictionary<string, int>();

    }
}

public class DeleteByVendor
{
    public string VendorID { get; set; }
    public string VendorName { get; set; }
    public string PricePage { get; set; }
    public string Description { get; set; }
}

Upvotes: 2

Views: 121

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

Group your list by PricePage first using GroupBy method. Then use ToDictionary to get a dictionary.

var results = vendorsForPages.GroupBy(v => v.PricePage)
                             .ToDictionary(g => g.Key,
                                           g => g.Select(x => x.VendorID)
                                                 .Distinct()
                                                 .Count());

Upvotes: 3

D Stanley
D Stanley

Reputation: 152566

You can group by PricePage then by VendorId:

var costPageVendorsCount = vendorsForPages.GroupBy(v => v.PricePage)
                                          .ToDictionary(g => g.Key, 
                                                        g => g.GroupBy(gg => gg.VendorID)
                                                              .Count()
                                                       );

Upvotes: 2

Related Questions