在linq查询结果中格式化日期 [英] format date in linq query result
问题描述
以下linq to实体查询给出以下结果:
The following linq to entities query gives the result below:
public class UserCountResult
{
public DateTime? date { get; set; } // **should this be string instead?**
public int users { get; set; }
public int visits { get; set; }
}
public JsonResult getActiveUserCount2(string from = "", string to = "")
{
var query = from s in db.UserActions
group s by EntityFunctions.TruncateTime(s.Date) into g
select new UserCountResult
{
date = g.Key, // can't use .toString("dd.MM.yyyy") here
users = g.Select(x => x.User).Distinct().Count(),
visits = g.Where(x => x.Category == "online").Select(x => x.Category).Count()
};
return Json(query, JsonRequestBehavior.AllowGet);
}
结果:
[{"date":"\/Date(1383433200000)\/","users":21,"visits":47},{"date":"\/Date(1383519600000)\/","users":91,"visits":236}]
我需要的日期格式不是"/Date(1383433200000)/",例如,
Instead of something like /Date(1383433200000)/, I need the date in format "dd.MM.yyyy", e.g.
[{"date":"29.11.2013","users":21,"visits":47},{"date":"30.11.2013","users":91,"visits":236}]
我没有找到关于如何更改查询格式的方法,而且我不确定该怎么做..我什至不知道为什么g.Key是可为null的..感谢您的任何输入!>
I found no way as to how to change the format in the query and I'm not sure what to do.. I don't even understand why g.Key is a nullable .. Thanks for any input!
推荐答案
g.Key
可为空,因为这是EntityFunctions.TruncateTime
的签名. http://msdn.microsoft.com/en-us/library/dd395596.aspx .
g.Key
is nullable because that's the signature of EntityFunctions.TruncateTime
. http://msdn.microsoft.com/en-us/library/dd395596.aspx.
要从Linq退出到实体,您可以保留查询不变,并在事实发生后对其进行投影:
To exit from Linq to Entities, you can leave the query as is, and project it after the fact:
return Json(query.AsEnumerable().Select(r => new
{
date = r.date.GetValueOrDefault().ToString("dd.MM.yyyy"),
users = r.users,
visits = r.visits
}), JsonRequestBehavior.AllowGet);
这不漂亮,但这就是Linq to Entities.
It's not pretty, but that's Linq to Entities for you.
这篇关于在linq查询结果中格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!