我建议使用一个小的 Func<TIn, TOut>
委托来将你的字符串日期转换成 DateTime,然后它们就可以被正确地排序了。
首先,将日期字符串转换为 DateTime
对象的简单方法:
Func<string, DateTime> getDate = s => {
int[] dateParts = s
.Split(new char[] {'-'})
.Select(dp => int.Parse(dp))
.ToArray();
return new DateTime(dateParts[0], dateParts[1], 1);
};
你的代码可能类似于这个样子;我无法测试你的代码,所以还需要你自己让它工作:
注意,我将你的Linq
查询分离出来,并在C#中进行排序;这样你就可以按照任何想要的方式从数据库中获取数据,然后对项目进行排序。我希望这能够正常工作;否则,你必须两次调用我的 getDate Func
-- 一次在 orderby
,一次在 select
;但我不喜欢这个选项。
// The select now builds an anonymous object; You can also create a new class, ExamResultWithDate,
// for example, that has all fields of ExamResult plus a DateTime field; OR you can just add that
// property to the partial class generated by EF or Linq-to-Sql or whatever right on the ExamResult
// entity.
var executionQuery = (from x in db.ExamResult
where x.Student.Equals(iStudent)
select new { Entity = x, ActualDate = getDate(x.Date) }); // note select * as in your OP doesn't compile :)
var orderedQuery = executionQuery
.OrderBy(eq => eq.ActualDate)
.Select(er => er.Entity); // gets you just the entities in this case and discards the dates
要获取日期之间的差异,只需对最小日期进行简单的计算:
以下是您程序的伪代码;
DateTime minDate = executionQuery
.ToList()
.Select(o => o.ActualDate)
.Min();
Dictionary<DateTime, int> datesWithMonthDifference = executionQuery
.ToDictionary(
eq => eq.ActualDate
eq => ((eq.Year - minDate.Year) * 12) + eq.Month - minDate.Month
);
这里有一个能够满足你需求的工作程序:请注意,这只是一个示例,需要根据你的项目进行调整。
using System;
using System.Collections.Generic;
using System.Linq;
namespace DateTimeFromString
{
class Program
{
static void Main(string[] args)
{
List<string> dates = new List<string>()
{
"2014-01",
"2013-04",
"2013-09"
};
Func<string, DateTime> getDate = s => {
int[] dateParts = s
.Split(new char[] {'-'})
.Select(dp => int.Parse(dp))
.ToArray();
return new DateTime(dateParts[0], dateParts[1], 1);
};
List<DateTime> sortedDates = dates
.Select(d => getDate(d))
.OrderBy(d => d)
.ToList();
Console.WriteLine(" Sorted Dates: ");
sortedDates.ForEach(d => Console.WriteLine(d.Year.ToString() + " - " + d.Month.ToString()));
DateTime minDate = sortedDates.Min();
Dictionary<DateTime, int> datesWithMonthDifference = sortedDates
.ToDictionary(
sd => sd,
sd => ((sd.Year - minDate.Year) * 12) + sd.Month - minDate.Month
);
Console.WriteLine();
Console.WriteLine("Sorted dates with month difference:");
foreach (var key in datesWithMonthDifference.Keys)
{
Console.WriteLine("{0} has difference of {1}", key, datesWithMonthDifference[key]);
}
Console.ReadKey();
}
}
}
我的测试程序的结果如下所示:
![enter image description here](https://istack.dev59.com/MkDx5.webp)
。
这句话意思是,某人在测试他的程序时得到了一个类似于图片的结果。