2013-11-22 2 views
2

나는 DeleteByVendor 개체 목록을 가지고 있습니다. 공급 업체와 가격 페이지라는 두 개의 비즈니스 엔티티가 있습니다. 하나의 가격 페이지에는 여러 공급 업체가있을 수 있습니다. 가격 페이지.사용자 지정 엔티티 목록에서 사전을 만드는 가장 좋은 LINQ 방법

각 가격 페이지와 해당 가격 페이지에있는 (distinct) 공급 업체 수를 가질 사전을 만들어야합니다. 하나의 가격 페이지는 해당 사전에 한 번만 표시되어야합니다.

LINQ chain method 접근 방법을 사용하여 어떻게 할 수 있습니까?

참고 : (중복 레코드가 있지만) 카운트가 PricePage에 의해

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

답변

3

그룹 목록 1이어야한다 "P3"먼저 GroupBy 방법을 사용하여. 그런 다음 ToDictionary을 사용하여 사전을 얻으십시오.

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

그러나 그것은 1 – Lijo

+0

을해야합니다 수를 2로 보여주고있다 "P3"들어 .. 유일한 공급 업체 수를 참가 @ Lijo 지금 확인하십시오. 내 대답을 업데이트했습니다. – MarcinJuraszek

2

그룹화 할 수 있습니다 다음 PricePage에 의해 VendorId의 :

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