简体   繁体   English

数组查找当前日期之前的所有日期

[英]Array find all dates before current date

Hello I am currently trying to array.find all the dates before the current date. 您好,我目前正在尝试array.find当前日期之前的所有日期。 I have tried both using the datetime.now as well as creating a seperate variable for current date in my struct but i keep getting "Cannot implicitly convert type 'Assignment_3.Program.Hire' to 'System.DateTime". 我已经尝试过使用datetime.now以及在我的结构中为当前日期创建一个单独的变量,但是我不断收到“无法将类型'Assignment_3.Program.Hire'隐式转换为'System.DateTime”。 I'm sure the solution is quite simple but as a novice it does escape from me. 我敢肯定解决方案非常简单,但是作为一个新手,它的确可以从我这里逃脱。 If you need any more of the code I will be happy to provide 如果您需要更多代码,我们将很乐意提供

 struct Hire
    {
        public int CustomerNo;
        public int DVDNo;
        public DateTime HireDate;
        public int NoNights;
        public DateTime CurrentDate = DateTime.Now;
    }


 DateTime result = Array.Find(hiredetails, Hire => Hire.HireDate <= Hire.CurrentDate);

Array.Find<T> returns the element matching the criteria. Array.Find<T>返回与条件匹配的元素。 In you case since it is an array of Hire type, it will return element of type Hire , which you cannot assign to DateTime . 在你的情况下,因为它是一个数组Hire类型,它会返回类型的元件Hire ,它不能分配给DateTime You can do: 你可以做:

List<DateTime> allDates = hiredetails.Where(hire=> hire.HireDate <= hire.CurrentDate)
                          .Select(r=> r.HireDate)
                          .ToList();

You can also return IEnumerable<DateTime> and exclude ToList() from the above statement. 您还可以返回IEnumerable<DateTime>并从上述语句中排除ToList()

Not really sure if you need this but instead of keeping the current date inside the object you can have that in your local variable and pass that in your query like: 不确定是否需要此方法,而不是将当前日期保留在对象中,可以将其保存在本地变量中,然后在查询中传递该日期,例如:

DateTime currentDate = DateTime.Now;
List<DateTime> allDates = hiredetails.Where(hire=> hire.HireDate <= currentDate)
                          .Select(r=> r.HireDate)
                          .ToList();

Do not store current date in a structure, use local variable instead, solution would look like: 不要将当前日期存储在结构中,而是使用局部变量,解决方案如下所示:

var currentDate = DateTime.Now;
var result = hiredetails.Select(h => h.HireDate).Where(d => d <= currentDate);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM