【问题标题】:How to replace datetime in var list with date linq如何用日期 linq 替换 var 列表中的日期时间
【发布时间】:2015-05-05 17:43:07
【问题描述】:

我有一个我在查询中创建的 var 列表,有一个名为 Fecha 的字段存储日期时间,我只想存储日期,但如果我在 linq 查询中运行属性 Date 它说它不能识别方法,所以我必须在创建列表后执行。

using (ProfesionalesEmpresasEntities bd = new ProfesionalesEmpresasEntities())
{

    var resultado = (from registroLlamadas in bd.RegistroLlamadas
                    join contacto in bd.Contactos on registroLlamadas.realizadaHacia equals contacto.id
                    select new { Fecha = registroLlamadas.fechaLlamada }).
                    ToList();    
}

【问题讨论】:

  • 你能给出确切的错误吗?
  • 您可能希望缩减缩进以获得更好的可读性。
  • 为什么不呢,Fetcha = registroLlamadas.fechaLlamada.Date
  • 使用 EntityFunctions.TruncateTime 或 SqlFunctions.DatePart 代替 Date 属性。

标签: c# linq date


【解决方案1】:

您只能在 LINQ 上指定 Date 属性以进行对象查询,因为您已经使用 ToList 迭代了您的查询,您可以这样做:

var resultado = (from registroLlamadas in bd.RegistroLlamadas
    join contacto in bd.Contactos on registroLlamadas.realizadaHacia equals contacto.id
    select new
    {

        Fecha = registroLlamadas.fechaLlamada

    }).AsEnumerable() //Bring it in memory or leave it as `ToList`
    .Select(row => new
    {

        Fecha = row.Fecha.Date,

    }).ToList();

或者,如果您不想修改当前查询或混合查询/方法表达式,请使用现有的 resultado 对象,例如:

resultado = resultado.Select(r=> new { Fecha = r.Fecha.Date }).ToList();

【讨论】:

    猜你喜欢
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    相关资源
    最近更新 更多