3 回答
TA贡献1783条经验 获得超4个赞
您应该首先选择重复部分并在后续查询中使用这些部分。这在查询语法中要容易得多,使用let关键字:
var result = from conts in _context.Contacts
where conts.CreatorUserId == _userManager.GetUserId(this.User)
let monthsSorted = conts.NpaInfo.NpaData.OrderByDescending(x => x.DataMonth)
let firstMonth = monthsSorted.FirstOrDefault()
let prevMonth = monthsSorted.Skip(1).FirstOrDefault()
select new
{
conts.ID,
conts.Mobile,
conts.Email,
conts.Facebook,
conts.StateId,
conts.CreatorUserId,
conts.Birthday,
conts.Description,
conts.Name,
conts.Photo,
conts.SecondName,
Tags = conts.Tags.Select(d=> d.UserTag.Emoji),
NpaId = conts.NpaInfo.NpaId,
PartnerPvPrev = prevMonth.MyPV,
GroupPvPrev = prevMonth.GroupPV,
LevelPrev = prevMonth.PerformanceBonusLevelId,
PartnerPv = firstMonth.MyPV,
GroupPv = firstMonth.GroupPV,
Level = firstMonth.PerformanceBonusLevelId,
EntryDate = conts.NpaInfo.EntryDate,
ExpirationDate = conts.NpaInfo.ExpirationDate
};
TA贡献2037条经验 获得超6个赞
做这样的事情将显着改善查询。
var result = conts.NpaInfo.NpaData.OrderByDescending(x => x.DataMonth).Take(2).ToArray();
PartnerPvPrev = result.Skip(1).Take(1).Select(x => x.MyPV).FirstOrDefault();
GroupPvPrev = result.Skip(1).Take(1).Select(x => x.GroupPV).FirstOrDefault();
LevelPrev = result.Skip(1).Take(1).Select(x => x.PerformanceBonusLevelId).FirstOrDefault();
PartnerPv = result.Take(1).Select(x => x.MyPV).FirstOrDefault();
Level = result.Take(1).Select(x => x.PerformanceBonusLevelId).FirstOrDefault();
GroupPv = result.Take(1).Select(x => x.GroupPV).FirstOrDefault();
TA贡献1845条经验 获得超8个赞
您应该使用 GroupBy :
class Program
{
static void Main(string[] args)
{
Conts conts = new Conts();
List<NpaDatas> data = conts.NpaInfo.NpaDatas
.OrderByDescending(x => x.DataMonth)
.GroupBy(x => x.DataMonth).Select(x => x.FirstOrDefault()).ToList();
//To get the second latest use followng
NPaDatas results = data.Skip(1).FirstOrDefault();
}
}
public class NpaDatas
{
public string NpaInfoId { get; set; }
public DateTime DataMonth { get; set; }
public PV PartnerPv { get; set; }
public PV PerformanceBonusLevelId { get; set; }
public PV GroupPv { get; set; }
}
public class PV
{
//data not specified
}
public class Conts
{
public NpaInfo NpaInfo { get; set; }
}
public class NpaInfo
{
public string ID { get; set; }
public List<NpaDatas> NpaDatas { get; set; }
}
- 3 回答
- 0 关注
- 150 浏览
添加回答
举报