Linq查询2个表按日期排序

时间:2015-10-07 08:34:36

标签: c# mysql linq

这里描述2个表

评论表

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

现在从两个表中我想获取列表日期明智。

意味着OutPut将是

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查询??

2 个答案:

答案 0 :(得分:0)

根据您的评论,您可以尝试以下查询 -

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;

答案 1 :(得分:0)

    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);

如上所述设置类,LINQ查询应如下所示:

{{1}}