LINQ选择具有最小日期值的行

时间:2014-02-24 08:47:39

标签: linq c#-4.0 linq-to-objects

我有这个linq查询:

    var query = from mpItem in MPay
                where mpItem.EndDate > System.DateTime.Now.Date
                group mpItem by mpItem.IdGroup into mpItemGrouped
                let minEndDate = mpItemGrouped.Min(p => p.EndDate)
                select new
                {
                    Id = mpItemGrouped.Key,
                    EndDate = mpItemGrouped.Min(p => p.EndDate),
                    Name = mpItemGrouped.Min(p => p.IdGroupModel.GroupName),
                    Price = mpItemGrouped.Min(p => p.PaySumIndividual)
                };

此查询应为每个 IdGroup 选择具有最小 EndDate 的行 此查询正在选择具有其他行值的最小 EndDate

1 个答案:

答案 0 :(得分:1)

EndDate按升序排序,并从组中选择第一项 - 这将是具有最小日期的项目。然后在select语句中使用此项

   var query = from MPayItem in MPay
                where mpItem.EndDate > System.DateTime.Now.Date
                group mpItem by mpItem.IdGroup into mpItemGrouped
                let minItem = mpItemGrouped.OrderBy(p => p.EndDate).First()
                select new
                {
                    Id = mpItemGrouped.Key,
                    EndDate = minItem.EndDate,
                    Name = minItem.IdGroupModel.GroupName,
                    Price = minItem.PaySumIndividual
                };