[英]Linq average query and projection
我正在嘗試從評分表中獲得人們的平均評分,我對此有以下代碼。 我將結果投影到PersonVm類中
public IEnumerable SrchArtisansByBSSLR(string q, int s = 0, int l = 0, double z = 0)
{
var list = from item in _entities.People
where item.Skill.SkillName == q && item.StateId == s && item.LGAId == l && item.Ratings.Any(g => g.RatingValue == z)
group item by item.PersonId into d
select new PersonVm
{
PersonId = d.Key,
Rating = d.Average(x=>x.Ratings.Any(y=>y.RatingValue)),
LastName = item.LastName,
Skill = item.Skill.SkillName,
StateId = item.StateId,
LGAId = item.LGAId,
Address = item.Address,
Email = item.Email,
ImageSource = @"\Photos\" + item.ImageSource,
RegDate = item.RegDate
};
return list;
}
我收到以下錯誤
無法將lambda表達式轉換為委托類型'System.Func',因為該塊中的某些返回類型不能隱式轉換為委托返回類型
和
無法隱式轉換類型“ double”? 到“布爾” ArtsHub.DataLayer
請問我的平均代碼有什么問題?
此x=>x.Ratings.Any(y=>y.RatingValue)
返回bool
作為結果,因為.Any()
產生boolean
結果類型,因此您需要為.Average()
獲得一個lambda
,后者產生的type
相同作為Rating
屬性的類型。
看來Rating
是double?
所以您需要一個lambda
傳遞給.Average()
,該返回一個double?
或double
或某些東西可以轉換為double?
我認為你需要這個:
Rating = d.Average(x => x.Ratings.Sum(y => y.RatingValue))
您需要將它們添加到group by
。
var list = from item in _entities.People
where item.Skill.SkillName == q && item.StateId == s && item.LGAId == l && item.Ratings.Any(g => g.RatingValue == z)
group item by new {
item.PersonId,
item.LastName,
item.Skill.SkillName,
item.StateId,
item.LGAId,
item.Address,
item.Email,
item.ImageSource,
item.RegDate
} into d
select new PersonVm
{
PersonId = d.Key,
Rating = d.Average(x => x.Ratings.Any(y => y.RatingValue)),
LastName = d.Key.LastName,
Skill = d.Key.SkillName,
StateId = d.Key.StateId,
LGAId = d.Key.LGAId,
Address = d.Key.Address,
Email = d.Key.Email,
ImageSource = @"\Photos\" + d.Key.ImageSource,
RegDate = d.Key.RegDate
};
return list;
注意... .GroupBy(item => new ...
之前的.ToList()
導致您的數據首先在內存中獲取,而group by
將在內存中完成,您可以比較這兩個查詢的執行時間。
var list = _entities.People
.Where(item => item.Skill.SkillName == q &&
item.StateId == s &&
item.LGAId == l &&
item.Ratings.Any(g => g.RatingValue == z))
.ToList()
.GroupBy(item => new
{
item.PersonId,
item.LastName,
item.Skill.SkillName,
item.StateId,
item.LGAId,
item.Address,
item.Email,
item.ImageSource,
item.RegDate
})
.Select(d => new PersonVm()
{
PersonId = d.Key,
Rating = d.Average(x => x.Ratings.Any(y => y.RatingValue)),
LastName = d.Key.LastName,
Skill = d.Key.SkillName,
StateId = d.Key.StateId,
LGAId = d.Key.LGAId,
Address = d.Key.Address,
Email = d.Key.Email,
ImageSource = @"\Photos\" + d.Key.ImageSource,
RegDate = d.Key.RegDate
})
.ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.