C#在几个月内获得差异?
我正在C#开发一个项目。我有一个名为C#在几个月内获得差异?,c#,mysql,sql,linq,C#,Mysql,Sql,Linq,我正在C#开发一个项目。我有一个名为ExamResult的模型,它有一个名为Date的字段,定义为String 然后我定义如下 var executionQuery = (from x in db.ExamResult where x.Student.Equals(iStudent) orderby x.Date select *); 日期以- 像这样
ExamResult
的模型,它有一个名为Date
的字段,定义为String
然后我定义如下
var executionQuery = (from x in db.ExamResult
where x.Student.Equals(iStudent)
orderby x.Date
select *);
日期以-
像这样
2014-01
2013-04
2013-09
我想做的是创建一个表,该表获取返回的所有日期的最小值,并创建一个表,该表与该最小日期的差值以月为单位
例如:
当我们得到上述结果时,我想得到下表(如果我们得到最小值为2013-04)
我尝试执行以下操作,但得到一个System.NotSupported
异常
var dates = executionQuery.Select(x => int.Parse(x.Date.Substring(0,
4)) * 12 + int.Parse(x.Date.Substring(5, 2)) -
int.Parse(minDate.Substring(0, 4)) * 12 -
int.Parse(minDate.Substring(5, 2)));
你知道我怎么做吗?将字符串转换为实际的“DateTime”对象会使事情变得更简单
// Getting DateTime objects instead of strings
var dates = executionQuery.ToArray().Select(
x => DateTime.ParseExact(x.Date,"yyyy-MM", CultureInfo.InvariantCulture));
// calculating smallest date
var minDate = dates.Min(x => x);
// this will help you get a collection of integers
var diffDates = dates.Select(
x => ((x.Year - minDate.Year) * 12) + x.Month - minDate.Month);
我将使用一个小的
Func
委托将字符串日期转换为日期时间,然后它们可以正确排序
首先,将日期字符串转换为DateTime
对象的简单方法:
// Split the string and instantiate new DateTime object to sort by later
Func<string, DateTime> getDate = s => {
int[] dateParts = s
.Split(new char[] {'-'})
.Select(dp => int.Parse(dp))
.ToArray();
// Let's use the new DateTime(int year, int month, int day) constructor overload
// dateParts[0] is the year and dateParts[1] is the month;
// the magic number 1 below is just a day to give to the DateTime constructor
return new DateTime(dateParts[0], dateParts[1], 1);
};
要获得不同的日期,只需对最短日期做一些简单的计算:
同样,这是程序的伪代码
// Let's get the minimum date and difference in months;
DateTime minDate = executionQuery
.ToList()
.Select(o => o.ActualDate)
.Min();
// I am just using the dates here but you can easily use your entire entity or whatever you need
Dictionary<DateTime, int> datesWithMonthDifference = executionQuery
.ToDictionary(
eq => eq.ActualDate
eq => ((eq.Year - minDate.Year) * 12) + eq.Month - minDate.Month // this formula calculates month difference as an integer
);
//让我们以月为单位获取最小日期和差值;
DateTime minDate=executionQuery
托利斯先生()
.选择(o=>o.ActualDate)
.Min();
//我只是在这里使用日期,但你可以很容易地使用你的整个实体或任何你需要的
Dictionary datesWithMonthDifference=执行查询
.ToDictionary(
eq=>eq.实际日期
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"
};
// Split the string and instantiate new DateTime object to sort by later
Func<string, DateTime> getDate = s => {
int[] dateParts = s
.Split(new char[] {'-'})
.Select(dp => int.Parse(dp))
.ToArray();
// Let's use the new DateTime(int year, int month, int day) constructor overload
// dateParts[0] is the year and dateParts[1] is the month;
// the magic number 1 below is just a day to give to the DateTime constructor
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()));
// Let's get the minimum date and difference in months;
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();
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
命名空间DateTimeFromString
{
班级计划
{
静态void Main(字符串[]参数)
{
列表日期=新列表()
{
"2014-01",
"2013-04",
"2013-09"
};
//拆分字符串并实例化新的DateTime对象,以便以后按其排序
Func getDate=s=>{
int[]dateParts=s
.Split(新字符[]{'-'})
.Select(dp=>int.Parse(dp))
.ToArray();
//让我们使用新的DateTime(int year、int month、int day)构造函数重载
//dateParts[0]为年,dateParts[1]为月;
//下面的神奇数字1只是给DateTime构造函数的一天
返回新的DateTime(dateParts[0],dateParts[1],1);
};
列表日期=日期
.选择(d=>getDate(d))
.OrderBy(d=>d)
.ToList();
Console.WriteLine(“排序日期:”);
sortedDates.ForEach(d=>Console.WriteLine(d.Year.ToString()+“-”+d.Month.ToString());
//让我们得到最小日期和月差;
DateTime minDate=sortedDates.Min();
Dictionary datesWithMonthDifference=sortedDates
.ToDictionary(
sd=>sd,
sd=>((sd.Year-minDate.Year)*12)+sd.Month-minDate.Month
);
Console.WriteLine();
Console.WriteLine(“带月差的排序日期:”);
foreach(datesWithMonthDifference.Keys中的变量键)
{
WriteLine(“{0}具有{1}”的差异,键,datesWithMonthDifference[key]);
}
Console.ReadKey();
}
}
}
我的测试程序的结果如下所示:
非常感谢Anri的回答。我很想尝试一下,但是我得到了一个错误,它说,
“方法'ParseExact'的重载没有包含两个参数”
在var dates=query.Select(x=>DateTime.ParseExact(x.Date+“-01”,“yyyy-MM-dd”)代码>。我做错什么了吗?@user2327751修复了'ParseExact'方法调用,请立即尝试。事实上,在日期字符串后面附加“-01”是不必要的,因为您可以简单地将格式指定为“yyyy-mm”。@Georg不确定它是否将使用第一天,但是的,有意义,谢谢我尝试了Anrie,但是我得到了这个异常System.Data.Entity.dll,但没有在用户代码中处理其他信息:LINQ to Entities不识别“System.DateTime ParseExact(System.String,System.String,System.IFormatProvider)”方法,而且此方法无法转换为存储表达式。
为什么不在模式中为日期使用DateTime?@DavidKhaykin非常感谢David。这是最合乎逻辑的做法。但是数据库不是我的:)我的系统需要与该数据库交互,但我们没有任何所有者权限。你对代码有什么建议吗?当然,请看我的答案:)
// Let's get the minimum date and difference in months;
DateTime minDate = executionQuery
.ToList()
.Select(o => o.ActualDate)
.Min();
// I am just using the dates here but you can easily use your entire entity or whatever you need
Dictionary<DateTime, int> datesWithMonthDifference = executionQuery
.ToDictionary(
eq => eq.ActualDate
eq => ((eq.Year - minDate.Year) * 12) + eq.Month - minDate.Month // this formula calculates month difference as an integer
);
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"
};
// Split the string and instantiate new DateTime object to sort by later
Func<string, DateTime> getDate = s => {
int[] dateParts = s
.Split(new char[] {'-'})
.Select(dp => int.Parse(dp))
.ToArray();
// Let's use the new DateTime(int year, int month, int day) constructor overload
// dateParts[0] is the year and dateParts[1] is the month;
// the magic number 1 below is just a day to give to the DateTime constructor
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()));
// Let's get the minimum date and difference in months;
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();
}
}
}