【问题标题】:Linq Query for 2 tables Order By Date [closed]2个表的Linq查询按日期排序[关闭]
【发布时间】:2015-10-07 08:34:35
【问题描述】:

这里描述 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

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

表示输出将是

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

【问题讨论】:

  • 你能展示一些你正在尝试的代码吗?
  • 我正在考虑合并评论和分享的所有数据,并对它们应用日期明智的排序。但不知道如何结合所有数据?因为我想仅按日期降序获取 10 个最高数据
  • 输出的最后一行来自哪里?为什么输出中只有三行?

标签: c# mysql linq


【解决方案1】:
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);

【讨论】:

    【解决方案2】:

    根据您的意见,您可以尝试以下查询-

    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;
    

    【讨论】:

    • 谢谢.. 它有效。将 sql 查询更改为 linq
    猜你喜欢
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    相关资源
    最近更新 更多