2013-06-05 56 views
0

我有以下類從通用的清單有另一個泛型列表

public class SearchResponse 
{ 
     public string SearchTerm { get; set; } 
     public List<DataClass> lstDataClass 
     public string Category { get; set; } 

} 

public DataClass 
{ 
     public String Date { get; set; } 
     public string NoOfRecord { get; set; } 
} 

我將通過SearchResponse類的SearchtermDataClassDate分組是具有List<SearchResponse>和 我想有NoOfRecord的總和獲取屬性的總和

假設

SearchResponse1 
{ 
    SearchTerm="A"; 
    Category="cata"; 
    ListOfDataClass 
    { 
     dataclass 
      { 
      5 may 2013, 
      50 
      } 
     dataclass 
     { 
       6 may 2013, 
       68 
     } 
    } 
} 


SearchResponse2 
{ 
    SearchTerm="A"; 
    Category="catb"; 
    ListOfDataClass 
    { 
     dataclass 
      { 
      5 may 2013, 
      52 
      } 
     dataclass 
     { 
       6 may 2013, 
       63 
     } 
    } 
} 


SearchResponse3 
{ 
    SearchTerm="B"; 
    Category="catc"; 
    ListOfDataClass 
    { 
     dataclass 
      { 
      5 may 2013, 
      48 
      } 
     dataclass 
     { 
       6 may 2013, 
       21 
     } 
    } 
} 

我想

SearchTerm="A", Date=5 May 2013, TotalRecords=102 
SearchTerm="A", Date=6 May 2013, TotalRecords=131 
SearchTerm="B", Date=6 May 2013, TotalRecords=48 
. 
. 
. 

回答

1

一個LINQ溶液是這樣的:

from x in 
(
    from sr in SearchResponse 
    from dc in sr.DataClass 
    select new { sr.SearchTerm , dc } 
) 
group x by new { x.SearchTerm, x.dc.Date } into g 
select new { 
       g.Key.SearchTerm, 
       g.Key.Date, 
       TotalRecords = g.Sum(g1 => g1.p.NoOfRecord) 
      } 

其中第一創建其中SearchtermDate可以組合在一起的平面列表(new { sr.SearchTerm , dc })。隨後,在每個組中計算Sum

0

我認爲這是可以改善的,但是這是我沒有時間做的事:

在你的類
var searchTerms = searchResponseList.GroupBy(g => g.SearchTerm) 
       .Select(x => x.Key); 

      foreach (var searchTerm in searchTerms) 
      { 
       var matchingDataClasses = searchResponseList.Where(response => response.SearchTerm == searchTerm) 
        .SelectMany(response => response.lstDataClass); 

       // Output the data 
       var data = matchingDataClasses.GroupBy(g => g.Date) 
        .Select(x => new 
        { 
         SearchTerm = searchTerm, 
         Date = x.Key, 
         TotalRecords = x.Sum(dataClass => dataClass.NoOfRecord) 
        }); 
      } 

的一件事是NoOfRecord需要從一個字符串的改變int來使x.Sum()工作。