Split a entity collection into n parts

ⅰ亾dé卋堺 提交于 2019-12-11 03:15:04

问题


I have a database table.

  • First, I want to group by date time.
  • Then I want to only select the groups with n items.

My class looks like this:

public class VisitDate
{
  public int Id {get;set;}
  public int VisitMeDate {get;set;}
  .....
  .....
}

My SQL table is like below:

Id   Date
--- -----------------------
136 2012-05-09 10:00:00.000
167 2012-05-09 12:00:00.000
137 2012-05-10 10:00:00.000
168 2012-05-10 12:00:00.000
194 2012-05-10 14:00:00.000
138 2012-05-11 10:00:00.000
169 2012-05-11 12:00:00.000
195 2012-05-11 14:00:00.000
139 2012-05-12 10:00:00.000
170 2012-05-12 12:00:00.000
196 2012-05-12 14:00:00.000
140 2012-05-13 10:00:00.000
171 2012-05-13 12:00:00.000
197 2012-05-13 14:00:00.000
141 2012-05-14 10:00:00.000
142 2012-05-15 10:00:00.000
172 2012-05-15 12:00:00.000
143 2012-05-16 10:00:00.000
173 2012-05-16 12:00:00.000
144 2012-05-17 10:00:00.000
174 2012-05-17 12:00:00.000
198 2012-05-17 14:00:00.000

I want to transform like below:

List<List<MyEntity>> = ?;

137 2012-05-10 10:00:00.000
168 2012-05-10 12:00:00.000
194 2012-05-10 14:00:00.000

138 2012-05-11 10:00:00.000
169 2012-05-11 12:00:00.000
195 2012-05-11 14:00:00.000

139 2012-05-12 10:00:00.000
170 2012-05-12 12:00:00.000
196 2012-05-12 14:00:00.000

140 2012-05-13 10:00:00.000
171 2012-05-13 12:00:00.000
197 2012-05-13 14:00:00.000

144 2012-05-17 10:00:00.000
174 2012-05-17 12:00:00.000
198 2012-05-17 14:00:00.000

I tried this:

List<List<VisitDate>> dates = dbContext.VisitDates.GroupBy(f => new { f.VisitMeDate }).ToList();

But it doesn't compile and I don't know how to say that I only want groups with three elements.


回答1:


Try something like this:

var result = dbContext.VisitDates
                      .GroupBy(x => x.VisitMeDate.Date)
                      .Where(g => g.Count() == 3)
                      .Select(g => g.ToList())
                      .ToList();


来源:https://stackoverflow.com/questions/10523718/split-a-entity-collection-into-n-parts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!