【问题标题】:How to group by month in LINQ query? [closed]如何在 LINQ 查询中按月分组? [关闭]
【发布时间】:2013-09-01 08:23:32
【问题描述】:

我做了这个 LINQ 查询

var db = new DataEntities();
var records = db.Table_1.GroupBy(x => x.date).tolist();

其中 Table_1 列的类型

ColumnName       dataType

id               numeric
date             datetime

table_1 中的记录:

1          3/May/2013
2          4/Apr/2013
3          7/May/2013

我想根据月份对 Table_1 的所有记录进行分组

var records = db.Table_1.GroupBy(x => x.date.Month);

有什么办法吗?

【问题讨论】:

  • 你得到什么错误?你在用什么,Entity Framework 还是 LINQ-to-SQL?
  • 它没有给我 x.date.month 的选项

标签: c# sql linq datetime group-by


【解决方案1】:

如果您使用的是实体框架,您可以使用SqlFunctions.DatePart

.GroupBy(x => SqlFunctions.DatePart("m", x.date))

【讨论】:

  • 它没有给我 SqlFunctions.DatePart 是否有任何参考要添加
  • 谢谢我明白了它的工作原理
【解决方案2】:

我找到了正确的答案,这对你也有帮助......

  System.Globalization.DateTimeFormatInfo DFI=new System.Globalization.DateTimeFormatInfo();
            var InvoiceDetailMonthwise = (from t in clsGlobalObjectRefrances.SchoolSoulController.Stt.ssspAccInvoiceBook(clsSchoolSoulObjects.OAcdSchoolInfo.SchoolId,clsSchoolSoulObjects.OAcdSchoolInfo.CurrentActiveSessionId )
                                          group t by new { t.VDate.Value.Month} 
                                              into grp
                                              select new lcclsInvoiceBook
                                              {
                                                  Month=DFI.GetMonthName( grp.Key.Month).ToString(),
                                                  Debit = grp.Sum(t => t.DebitAmount) > 0 ? 0 : -(grp.Sum(t => t.DebitAmount)),
                                                  Credit = grp.Sum(t => t.CreditAmount ) > 0 ? (grp.Sum(t => t.CreditAmount )) : 0,

                                              }).ToList();



            dgvInvoiceBook.DataSource = InvoiceDetailMonthwise;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多