2014-10-06 69 views
0

你好,我目前正在尝试array.find当前日期之前的所有日期。我已经尝试使用datetime.now以及在我的结构中为当前日期创建一个单独的变量,但我一直收到“不能隐式地将类型'Assignment_3.Program.Hire'转换为'System.DateTime'。我相信这个解决方案很简单,但作为一个新手,它确实从我身上逃脱了。如果您需要更多的代码,我会很乐意提供Array查找当前日期前的所有日期

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

回答

3

Array.Find<T>返回符合条件的元素。在你的情况下,因为它是一个Hire类型的数组,它将返回Hire类型的元素,你不能指定给DateTime。你可以这样做:

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

您也可以从上面的语句返回IEnumerable<DateTime>和排除ToList()

不能确定,如果你需要,但不是让你可以在你的本地变量,并通过在您的查询,如对象内的当前日期是:

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

看起来像我一个星期左右早,但如果我不跨你很快再次运行:欢迎到100K俱乐部。 – 2014-10-06 21:18:56

+0

@JoelCoehoorn,在此先感谢:) – Habib 2014-10-06 21:20:06

+0

我相信你错过了'.Select',因为hireDetails很可能是'Hire []'类型。 – 2014-10-06 21:24:44

0

不要存放当前日期的结构,使用本地变量代替,解决办法是这样的:

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