从自定义实体列表中创建字典的最佳LINQ方式

时间:2013-11-22 03:17:22

标签: c# linq

我有一个DeleteByVendor对象列表..它有两个业务实体 - 供应商和价格页面。一个价格页面可以有多个供应商..并且一个供应商可以存在多个价格页面。

我们需要创建一个字典,其中包含每个pricepage和(distinct)个供应商在该pricepage中的数量。一个pricepage应该只存在于该字典中一次。

我们如何使用LINQ chain method方法来实现?

注意:对于“P3”,计数应为1(尽管存在重复记录)

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

2 个答案:

答案 0 :(得分:3)

首先使用PricePage方法按GroupBy对您的列表进行分组。然后使用ToDictionary获取字典。

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

答案 1 :(得分:2)

您可以按PricePage分组,然后按VendorId分组:

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