在Lambda Expression中按ID计算

时间:2013-11-28 20:36:46

标签: asp.net-mvc linq lambda count group-by

我有会议和城市表,并使用lambda表达式将它们加入。另一方面,我根据会议日期设置了“过期”属性,如下所示。我想使用Total属性代替下面的Expired属性,以便检查每个申请人的总数(具有相同的MeetingID )。在此帮助下,我可以确定会议表中同一会议(通过相同的会议ID)是否有50人,并阻止用户申请超过50人。

在我的下面的代码中,我使用根据MeetingDate属性设置的Expired参数。我需要指定像“Full”这样的属性,以便通过id获得每次会议的总申请人。我怎样才能在下面的Lambda表达式中执行此操作?


城市模型:

public class City
{
    public int CityID { get; set; }
    public string CityName { get; set; }
}    


会议模式:

public class Meeting
{
    public int MeetingID { get; set; }
    public string MeetingName { get; set; }
    public DateTime MeetingStartDate { get; set; }       
    public DateTime? MeetingEndDate { get; set; }
    public int? TotalParticipant { get; set; }
    public int? MeetingCityId { get; set; }
}


申请人型号:

public class Applicant
{
    [Key]
    public int ApplicantID { get; set; }
    public DateTime? SubmitDate { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }   
    public int MeetingId { get; set; } 
}


控制器:

var meetingsQuery = repository.Meetings
            .Join(repository.Cities, m => m.MeetingCityId, c => c.CityID,
                (m, c) => new
                {
                    CityID = c.CityID,
                    CityName = c.CityName,
                    MeetingDate = m.MeetingStartDate
                }
            )
            .OrderBy(x => x.CityID)
            .AsEnumerable()
            .Select(
                i => new
                {
                    Value = i.CityID.ToString(),
                    DisplayValue = string.Format(
                        "{0} ({1:dd MMMM yyyy})",
                        i.CityName, i.MeetingDate),
                    Expired = i.MeetingDate < DateTime.UtcNow,
                    Full = ... ???
                }
            ).ToList();

1 个答案:

答案 0 :(得分:1)

如果您的会议与申请人有关系,那么:

        var meetingsQuery = repository.Meetings
        .Join(repository.Cities, m => m.MeetingCityId, c => c.CityID,
            (m, c) => new
            {
                CityID = c.CityID,
                CityName = c.CityName,
                MeetingDate = m.MeetingStartDate,
                ApplicantsCount = m.Applicants.Count(),

            }
        )
        .OrderBy(x => x.CityID)
        .AsEnumerable()
        .Select(
            i => new
            {
                Value = i.CityID.ToString(),
                DisplayValue = string.Format(
                    "{0} ({1:dd MMMM yyyy})",
                    i.CityName, i.MeetingDate),
                Expired = i.MeetingDate < DateTime.UtcNow,
                Full = i.ApplicantsCount >= MaxApplicantsCount
            }
        ).ToList();