在linq和EF中按月排序 [英] Sort by month in linq and EF
问题描述
我有一个linq查询,它的内部是月份名称.我希望结果按月份(1月,2月,3月,...)排序.
I have a linq query and inside of it is the month name. I want the results sorted by the month (Jan, Feb, Mar, ...).
目前,我有以下内容,但它给了我错误:
Currently I have the below but it's giving me and error:
LINQ to Entities无法识别方法'System.DateTime Parse(System.String)'方法,并且此方法无法转换 进入商店表达式.
LINQ to Entities does not recognize the method 'System.DateTime Parse(System.String)' method, and this method cannot be translated into a store expression.
var shockValues = (from s in ctx.Shocks
where s.ID == id
orderby DateTime.Parse(s.MonthName)
select new
{
val = s.MonthName + "=" + s.ShockValue
});
推荐答案
您别无选择.您可以使用一长串可选的运算符将名称映射到数字
You've got few options. You could use a long list of optional operators to map the names to numbers
order by s.MonthName == "Jan" ? 1 : s.MonthName == "Feb" ? 2 : ...
您可以在数据库中创建一个表,将名称映射到数字值
You could create a table in your DB that maps the names to nummeric values
var shockValues = (from s in ctx.Shocks
join o in MonthOrder on s.MonthName equals o.MonthName
where s.ID == id
orderby o.MonthNumber
select new
{
val = s.MonthName + "=" + s.ShockValue
});
或者在内存中进行排序
var shockValues = (from s in ctx.Shocks
where s.ID == id
select new
{
s.MonthName,
s.ShockValue
})
.AsEnumerable()
.OrderBy(s => DateTime.ParseExact(s.MonthName, "MMM", CultureInfo.InvariantCulture).Month)
.Select(s => new
{
val = s.MonthName + "=" + s.ShockValue
});
这篇关于在linq和EF中按月排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!