Accepted answer

I'd try this:

if (tb_DateFrom.Text != "") {
    journeys = from j in journeys
               where j.DateTo.CompareTo(tb_DateFrom.Text) >= 0
               select j;

if (tb_DateTo.Text != "") {
    journeys = from j in journeys
               where j.DateFrom.CompareTo(tb_DateTo.Text) <= 0
               select j;


As the string format you have sorts in the same order as the dates they represent, I don't see why you have to convert their data format at all. Just do (untested):

journeys = from j in journeys
               where j.DateTo >= tb_DateFrom.Text && j.DateFrom >= tb_DateTo.Text
               select j;

Update, after Joakim's comment, still just using the sort order of the strings:

journeys = from j in journeys
           where j.DateTo.CompareTo(tb_DateFrom.Text) >= 0 && 
                 j.DateFrom.CompareTo(tb_DateTo.Text) <= 0
           select j;

(Det borde väl fungera, Joakim?)

Oops, I missed the accepted answer, but I'll still leave my first edit...


Why don't you convert textbox values to datetime and then compare the dates in the where clause, instead of converting to int

 DateTime? dateFrom = null, dateTo = null;

    dateFrom = DateTime.ParseExact(tb_DateFrom.Text, "yyyyMMdd", null);

 if (!String.IsNullOrWhiteSpace(tb_DateTo.Text))
    dateTo = DateTime.ParseExact(tb_DateTo.Text, "yyyyMMdd", null);

 if (dateFrom.HasValue)
    journeys = journeys.Where(j => j.DateFrom >= dateFrom.Value);

 if (dateTo.HasValue)
    journeys = journeys.Where(j => j.DateTo <= dateTo.Value);


private DateTime getDate(string yyyyMmDd, DateTime defaultValue)
  DateTime ret  = DateTime.MinValue;
  if (!DateTime.TryParse(yyyyMmDd, out ret)) 
     return defaultValue;

  return ret;

var to = DateTime.Parse(tb_DateTo.Text);
var from  = DateTime.Parse(tb_DateFrom.Text);
journeys.Where(j=> getDate(j.DateFrom, DateTime.MaxValue) <= from && getDate(j.DateTo, DateTime.MinValue) >= to);

Related Articles