Linq查询2个表按日期排序
本文关键字:日期 排序 查询 2个 Linq | 更新日期: 2023-09-27 18:16:27
这里描述两个表
注释表
ID Comment Id OrderDate
--- ---------- --------------------
1 1 2003-10-13 08:00:00
2 2 2003-10-12 10:00:00
3 1 2003-10-10 12:00:00
共享表
ID Share Id OrderDate
--- ---------- --------------------
1 1 2003-10-11 08:00:00
2 2 2003-10-15 10:00:00
2 2 2003-10-12 10:00:00
现在,我想从两个表中获取列表日期顺序。
意味着输出将是
ID OrderDate
--- -------------------
3 2003-10-10 12:00:00(Comment)
1 2003-10-11 08:00:00(Share)
3 2003-10-16 12:00:00(Comment)
我们如何生成Linq查询??
public class ShareEntry
{
public DateTime Date;
public int ID;
public int shareID;
}
public class CommentEntry
{
public DateTime Date;
public int ID;
public int commentID;
}
通过如上所述设置类,LINQ查询应该如下所示:
IEnumerable<ShareEntry> share = new List<ShareEntry>();
IEnumerable<CommentEntry> comment = new List<CommentEntry>();
var output = share
.Select(x => new
{
id = x.ID,
date = x.Date,
type = "share"
})
.Concat(comment.
Select(x => new
{
id = x.ID,
date = x.Date,
type = "comment"
}))
.OrderByDescending(x => x.date).Take(10);
根据您的备注,您可以尝试以下查询-
SELECT distinct id, orderdate FROM
(
SELECT id, orderdate FROM `comment`
UNION ALL
SELECT id, orderdate FROM `share`
) a
ORDER BY a.orderdate DESC
LIMIT 10;