组Linq并返回班级

时间:2013-06-19 09:40:59

标签: linq

我正在查询EF实体MatchHistory:

   public partial class MatchHistory
    {
        public System.Guid ApplicantId { get; set; }
        public int BuyerId { get; set; }
        public System.DateTime AppliedOn { get; set; }
        public int MatchResultId { get; set; }
        public System.DateTime ReapplyOn { get; set; }

        public virtual MatchBuyer MatchBuyer { get; set; }
    }

我目前在我的代码中有这个linq语句。

            return r.Find()
                .Where(x => x.AppliedOn > cutoff && x.MatchResultId == (int)MatchResult.Accepted)
                .ToList();

这将返回匹配条件的MatchHistory类型的所有行。

但是,我想要做的是按BuyerId分组并按BuyerId返回一个计数。

这是班级,我想输出到:

public class QuotaCount
{
    public int BuyerId { get; set; }
    public int Count { get; set; }
}

还没有完全找到合适的语法 - 任何建议都值得赞赏。

2 个答案:

答案 0 :(得分:2)

return r.Find()
        .Where(x => x.AppliedOn > cutoff && x.MatchResultId == (int)MatchResult.Accepted)
        .GroupBy(x => x.BuyerId)
        .Select(x => new QuotaCount { BuyerId = x.Key, Count = x.Count() })
        .ToList();

答案 1 :(得分:1)

return r.Find()
                .Where(x => x.AppliedOn > cutoff && x.MatchResultId == (int)MatchResult.Accepted)
                .GroupBy(mh=>mh.BuyerId).Select(gr=>new QuotaCount{BuyerId=gr.Key,Count=gr.Count});