繁体   English   中英

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

[英]Best LINQ way to create dictionary from list of custom entities

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

我们需要创建一个字典,其中将包含每个价格页以及该价格页中存在的( distinct )供应商数量。 一个价格页在该词典中只能出现一次。

我们如何使用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; }
}

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM