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 e
The best way and easiest way is create a stored procedure
Create procedure sortevents
as
SELECT *
FROM [SAGMJ].[dbo].[Events]
ORDER BY CASE
WHEN MONTH([StartAt]) = MONTH(GETDATE())
AND YEAR([StartAt]) = YEAR(GETDATE()) THEN 0
ELSE 1
END, [StartAt];
//Next call your sp
var v = (dc.sortevents()).ToList();
Something like this should work
var shockValues = ctx.Shocks.Where(s => s.ID == id).Select(x => new {x.MonthName, MonthNum = x.MonthName == "Jan" : 1 ? x.MonthName == "Feb" : 2 ? 0}).OrderBy(s => MonthNum).Select(s => new {val = s.MonthName + "=" + s.ShockValue}
If you dont want to create a table in your database, you can do like
var names = DateTimeFormatInfo.CurrentInfo.MonthNames
.Take(12).Select(s => new[] {s.Substring(0,3)});
And then order against a separate list.
orderby names.IndexOf(s.MonthName)
Try:
orderby Convert.ToDateTime(s.MonthName + " 1, " + DateTime.Now.Year.ToString()).Month
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
});
Or do the ordering in memory
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
});