2011-07-31 174 views
1

我有日期時間範圍:如何從日期範圍獲取日期時間列表?

var _checkInYear = (from d in db.bookings select d.checkinyear).ToList(); 
var _checkInMonth = (from d in db.bookings select d.checkinmonth).ToList(); 
var _checkInDay = (from d in db.bookings select d.checkinday).ToList(); 

var _checkOutYear = (from d in db.bookings select d.checkoutyear).ToList(); 
var _checkOutMonth = (from d in db.bookings select d.checkoutmonth).ToList(); 
var _checkOutDay = (from d in db.bookings select d.checkoutday).ToList(); 

我怎樣才能從這個範圍DateTime名單?例如,如果入住時間爲20/08/2011,並且23/08/2011需要在此範圍內列入日期時間。

20/08/2011,21/08/2011,22/08/2011,23/08/2011。

+2

嗯,這可能是問題的目的,一個人爲的例子,但我擔心這甚至不會做你想要什麼。你可能會更好使用'var checkInData = bookings.Select(new DateTime(d.CheckinYear,d.CheckinMonth,d.CheckinDay))。ToList();'等。除此之外,很難給你提供的東西回答你的問題。你能否進一步擴大? –

回答

3
DateTime checkIn = new DateTime(_checkInYear, _checkInMonth, _checkInDay); 
DateTime checkOut = new DateTime(_checkOutYear, _checkOutMonth, _checkOutDay); 

TimeSpan span = checkOut - checkIn; 
List<DateTime> range = new List<DateTime>(); 
for(int day = 0; day <= span.Days; day++) 
{ 
    range.Add(checkIn.AddDays(day)); 
} 

例子:http://www.ideone.com/BxmkF

2

算法很簡單,獲取你的出發點,遞增,直到你到達終點。

var startDate = new DateTime(checkInYear, checkInMonth, checkInDay); 
var endDate = new DateTime(checkOutYear, checkOutMonth, checkOutDay); 
var givenDate = startDate; 
var datesInRange = new List<DateTime>(); 

while (givenDate <= startDate) 
{ 
    datesInRange.Add(givenDate); 
    givenDate = givenDate.AddDays(1); 
} 

// work with/return datesInRange 
0

既然你讓你的手兩個日期,最好的辦法就是使用一個forwhile循環:

var dates = new List<DateTime>(); 
var curDate = booking.CheckinDate; 
while (curDate <= booking.CheckoutDate) 
{ 
    dates.Add(curDate); 
    curDate = curDate.AddDays(1); 
} 

然而,我很欣賞這可能是針對這個問題的一個人爲的例子,但我擔心你r示例代碼不會做你想要的。不要理會進一步閱讀,如果是這樣的話,我只是想強調它的關閉的機會,你可能會像這樣的東西更好:

var booking = (from b in data.Bookings 
       where b.BookingId = bookingId 
       select new BookingSearchResult // You have to create this class 
          { 
           CheckinDate = new DateTime(b.CheckinYear, b.CheckinMonth, b.CheckinDay), 
           CheckoutDate = new DateTime(b.CheckoutYear, b.CheckoutMonth, b.CheckoutDay) 
          }).SingleOrDefault(); 
1

如果你能得到檢查和退房退房手續日期,那麼你可以有一個擴展方法爲DateTime獲得列表:

public static class ExtensionMethods 
{ 
    static IEnumerable<DateTime> GetDateRange(this DateTime d, DateTime e) 
    { 
     var t=d; 
     do 
     { 
      yield return t; 
      t=t.AddDays(1); 
     }while(t<e); 
    } 
} 

然後使用它是這樣的:

var dateList = checkIn.GetDateRange(checkOutDate); 

測試中Linqpad。

0

有點老問題,但我想我們應該這樣做艾克說:

DateTime checkIn = new DateTime(_checkInYear, _checkInMonth, _checkInDay); 
DateTime checkOut = new DateTime(_checkOutYear, _checkOutMonth, _checkOutDay); 
List<DateTime> allDates = new List<DateTime>(); 

for (DateTime date = checkIn; date <= checkOut; date = date.AddDays(1)) 
    allDates.Add(date);