简体   繁体   中英

Array find all dates before current date

Hello I am currently trying to array.find all the dates before the current date. 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". 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. In you case since it is an array of Hire type, it will return element of type Hire , which you cannot assign to 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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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