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

我将拥有List<SearchResponse>并且我想通过对班级和班级进行分组来获得SearchtermNoOfRecordSearchResponseDate总和DataClass

认为

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
.
.
.
4

2 回答 2

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中计算。

于 2013-06-05T21:35:20.897 回答
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() 工作。

于 2013-06-05T16:59:56.500 回答