如何使用linq从datetime列中仅获取Date

use*_*485 4 linq asp.net linq-to-sql asp.net-mvc-2

我在数据库中有一列作为EffectiveDate

这是DateTime的类型.

我有一个linq查询从表中获取EffectiveDate.但是当我得到我的时候会得到EffectiveDate.

但在我的linq查询中,我只需要Date,我不想要有效时间.

如何编写Linq查询?

谢谢

hun*_*ter 11

Date在任何DateTime结构上调用属性

EffectiveDate.Date;
Run Code Online (Sandbox Code Playgroud)

或者打电话

EffectiveDate.ToShortDateString();
Run Code Online (Sandbox Code Playgroud)

或在此处调用更多DateTime格式时使用"d"格式.ToString()

EffectiveDate.ToString("d");
Run Code Online (Sandbox Code Playgroud)

编写Linq查询可能如下所示:

someCollection.Select(i => i.EffectiveDate.ToShortDateString());
Run Code Online (Sandbox Code Playgroud)

如果可以EffectiveDate为空,你可以尝试:

someCollection
    .Where(i => i.EffectiveDate.HasValue)
    .Select(i => i.EffectiveDate.Value.ToShortDateString());
Run Code Online (Sandbox Code Playgroud)

DateTime.Date属性

与此实例具有相同日期的新对象,时间值设置为午夜12:00:00(00:00:00).

DateTime.ToShortDateString方法

包含当前DateTime对象的短日期字符串表示形式的字符串.

  • @user如果您正在使用Entity框架,那么您是对的EDM.DateTime没有.Date属性.查看[EDM.DateTime](http://msdn.microsoft.com/en-us/library/bb387157.aspx)了解可以使用的方法. (2认同)