2
\$\begingroup\$

I feel like repeating myself but i don't know how to refactor this. Linq condition is the same but property to compare is different (BookingDate ,CheckInDate ,CheckOutDate)

    protected void FilterByDateRange(ref IEnumerable<ViewBooking> pObjListBooking)
    {
        DateTime startDate;
        DateTime endDate;

        startDate = DateTime.ParseExact(txtStartDate.Text, "d", System.Globalization.CultureInfo.CurrentCulture);
        endDate = DateTime.ParseExact(txtEndDate.Text, "d", System.Globalization.CultureInfo.CurrentCulture).AddDays(1);

        switch(ddlOrderBy.Text)
        {
            case "Booking Date":
                pObjListBooking = pObjListBooking.Where(item => item.BookingDate >= startDate && item.BookingDate < endDate);
            break;

            case "Check In Date":
                 pObjListBooking = pObjListBooking.Where(item => item.CheckInDate >= startDate && item.CheckInDate < endDate);
           break;

            case "Check Out Date":
                pObjListBooking = pObjListBooking.Where(item => item.CheckOutDate >= startDate && item.CheckOutDate < endDate);
            break;
        }
    }
\$\endgroup\$
4
\$\begingroup\$

You could do something like this, but I don't know, whether it's a good idea:

Func<ViewBooking,DateTime> getDate = null;
switch(...)
{
    case ...:
    getDate = (ViewBooking item) => item.BookingDate;
    break;
}

pObjListBooking = pObjListBooking.Where(item => getDate(item) >= startDate && getDate(item) < endDate);
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.