假设我有这种假设的多对多关系:
public class Paper
{
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<Author> Authors { get; set; }
}
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Paper> Papers { get; set; }
}
我想使用 LINQ 构建一个查询,该查询将为我提供每位作者与其他作者相比的“受欢迎程度”,即作者贡献的论文数量除以所有论文中作者贡献的总数。我想出了几个查询来实现这一点。
选项1:
var query1 = from author in db.Authors
let sum = (double)db.Authors.Sum(a => a.Papers.Count)
select new
{
Author = author,
Popularity = author.Papers.Count / sum
};
选项 2:
var temp = db.Authors.Select(a => new
{
Auth = a,
Contribs = a.Papers.Count
});
var query2 = temp.Select(a => new
{
Author = a,
Popularity = a.Contribs / (double)temp.Sum(a2 => a2.Contribs)
});
基本上,我的问题是:其中哪个更有效,还有其他更有效的单个查询吗?其中任何一个如何与两个单独的查询进行比较,如下所示:
double sum = db.Authors.Sum(a => a.Papers.Count);
var query3 = from author in db.Authors
select new
{
Author = author,
Popularity = author.Papers.Count / sum
};