从具有另一个通用列表的通用列表中获取属性的总和

时间:2013-06-05 16:44:30

标签: linq group-by generic-list

我有以下课程

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

我将List<SearchResponse>和。{ 我希望通过Searchterm SearchResponse类和Date DataClass

分组来获得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
.
.
.

2 个答案:

答案 0 :(得分: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) 
           }

首先创建一个平面列表(new { sr.SearchTerm , dc }),其中SearchtermDate可以组合在一起。随后,在每个组中计算Sum

答案 1 :(得分: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()工作。