gpt4 book ai didi

c# - 使用 Linq 从另一个表中获取按记录数排序的列表

转载 作者:太空宇宙 更新时间:2023-11-03 23:06:05 25 4
gpt4 key购买 nike

我正在使用 EF6 并创建了这两个模型:

public class Publication
{
public int Id { get; set; }
public string Name { get; set; }
public List<Product> Products { get; set; }
}

public class ViewLog
{
public int Id { get; set; }
public int? UserId { get; set; }
[ForeignKey("UserId")]
public User.User User { get; set; }
public int? SessionId { get; set; }
[ForeignKey("SessionId")]
public User.Session Session { get; set; }
public int PublicationId { get; set; }
[ForeignKey("PublicationId")]
public Publication.Publication Publication { get; set; }
public DateTime Created { get; set; }
}

每次访问 Publication 时,我都会在 ViewLog 表中创建一条新记录。现在,使用 Linq,我需要按照过去 24 小时内每个出版物的 ViewLogs(访问)数量对所有出版物进行排序。 (如果 Publication 没有 ViewLogs,它们也需要出现,但显然在有 viewlogs 的发布之后)

最佳答案

您可以使用 GroupJoin当您没有导航属性并且需要左外连接时

lambda 语法如下:

var publicationQuery = new List<Publication>().AsQueryable();
var viewLogQuery = new List<ViewLog>().AsQueryable();

var leftJoinQuery = publicationQuery
.GroupJoin(viewLogQuery, x => x.Id, x => x.PublicationId, (pub, logs) => new
{
PublicationId = pub.Id,
LogCount = logs.Count()
})
.OrderByDescending(x => x.LogCount);

我也找到了这个Query Expression Translation Cheat Sheet从查询表达式(更接近 SQL)到 lambda 方法语法(我更喜欢)非常有用

如果您有导航属性 Publication.ViewLogs (这是一个 List<ViewLog> ),那么你可以只使用 Select()有投影

var publicationQuery = new List<Publication>().AsQueryable(); // From a DbSet...

var query = publicationQuery
.Select(x => new
{
PublicationId = x.Id,
LogCount = x.ViewLogs.Count
})
.OrderByDescending(x => x.LogCount);

关于c# - 使用 Linq 从另一个表中获取按记录数排序的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41113093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com