【问题标题】:Linq to Sql Order by inside a group by not workingLinq to Sql Order by inside a group by not working
【发布时间】:2016-05-26 01:44:27
【问题描述】:

我的表中有此列。

Date
-----
2014-01-15
2014-05-03
.
.

我想使用 linq to Sql 运行这个查询:

SELECT 
    DATEPART(MONTH,date) as dateColumn
FROM 
    [mydatabase].[dbo].[global_currency_entries]
WHERE 
    date >= '2014-01-01' AND date<='2014-12-31'
GROUP BY
    DATEPART(Month,date)
ORDER BY 
    DATEPART(MONTH,date)

我正在使用的 Linq to sql 代码:

var timePeriod = (from gce in db.global_currency_entries
                  where gce.date >= Convert.ToDateTime("2014-01-01") && gce.date <= Convert.ToDateTime("2014-12-31")
                  orderby gce.date.Month 
                  group gce by new {gce.date.Month});

Orderby 在上述情况下不起作用。

foreach (var time in timePeriod)
{
    lblOutput.Text = lblOutput.Text + time.Key + ",";
}

我看到了这个输出:

{ Month = 9 },{ Month = 3 },{ Month = 12 },{ Month = 6 },{ Month = 7 },{ Month = 1 },{ Month = 10 },{ Month = 4 },{ Month = 5 },{ Month = 2 },{ Month = 11 },{ Month = 8 }, 

【问题讨论】:

  • 与 SQL 版本相比,您的组和排序子句颠倒了。为什么?
  • aaa 是我的错,,,我现在明白了,,,
  • 正确的方法是(from gce in db.global_currency_entries where gce.date &gt;= Convert.ToDateTime("2014-01-01") &amp;&amp; gce.date &lt;= Convert.ToDateTime("2014-12-31") select gce.date.Month).GroupBy(p =&gt; p).OrderBy(p =&gt; p.Key);

标签: asp.net c#-4.0


【解决方案1】:

我在 LinqPad 5 中编写了这个并且我能够让它工作。我在 LinqPad 中使用了 C# 程序。

void Main()
{
    List<global_currency_entries> gce = new List<global_currency_entries>();

    DateTime dt = new DateTime(2014, 12, 01);

    gce.Add(new global_currency_entries
    {
        date = dt
    });

    dt = new DateTime(2014, 12, 25);
    gce.Add(new global_currency_entries
    {
        date = dt
    });

    dt = new DateTime(2014, 09, 03);
    gce.Add(new global_currency_entries
    {
        date = dt
    });

    dt = new DateTime(2014, 09, 25);
    gce.Add(new global_currency_entries
    {
        date = dt
    });


    dt = new DateTime(2014, 07, 15);
    gce.Add(new global_currency_entries
    {
        date = dt
    });

    dt = new DateTime(2014, 07, 20);
    gce.Add(new global_currency_entries
    {
        date = dt
    });

    dt = new DateTime(2014, 05, 05);
    gce.Add(new global_currency_entries
    {
        date = dt
    });


    var result = (from x in gce
              where x.date >= Convert.ToDateTime("2014-01-01") && x.date <= Convert.ToDateTime("2014-12-31")
              orderby x.date.Month
              group x by new {x.date.Month}
              //select x
              );       

    foreach (var n in result)
        Console.Write (n.Key + "  |  ");         

}

public class global_currency_entries
{
    public DateTime date {get; set;}
}

我的结果是 { 月 = 5 } | { 月 = 7 } | { 月 = 9 } | { 月 = 12 } |

【讨论】:

    猜你喜欢
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 2017-02-06
    • 2011-06-28
    • 1970-01-01
    相关资源
    最近更新 更多