views:

185

answers:

2

I have a DataTable according to the Client Requirement it can contain invalid date say "00/00/1999",NULL,Empty String.(Typed DatSet)

When i collect them as enumerables i wish to convert any of those invalid forms to empty string.

(i.e)

 EnumerableRowCollection<DataRow> query = 
    from order in _table.AsEnumerable()
    select 
   new {
        OrderDate= 
        string.IsNullorEmpty(Convert.ToString(order.Field<DateTime>("OrderDate"))
        || 
        (How to check Date is Invalid  date)
         ? String.Empty : order.Field<DateTime>("OrderDate") 
        }

How to check whether a Date is a valid Date or not?

+2  A: 

DateTime.TryParse...like this given your current code:

 DateTime date;
 EnumerableRowCollection<DataRow> query = 

    from order in _table.AsEnumerable()
    select 
   new {
        OrderDate= 
        string.IsNullorEmpty(Convert.ToString(order.Field<DateTime>("OrderDate"))
        || 
        !DateTime.TryParse(Convert.ToString(order.Field<DateTime>("OrderDate")),out date)
         ? string.Empty : date.ToShortDateString() 
        }

(using notepad for an IDE so apologies if there's a syntax error but that should give you the general idea)

I'm assuming that OrderDate is a string since you are trying to assign it string.Empty, if its a DateTime then change the ternary assignment to something like DateTime.MinValue in place of the empty string (or whatever you want to use for your "invalid" dates, since an empty string is no longer an option) :

? DateTime.MinValue:date

or if OrderDate is a nullable DateTime then

? null:date
kekekela
Both values of the ternary operator have to be of the same type. You can't have one be a DateTime and the other be a string.
tvanfosson
@tvanfosson Thanks, noticed that after I posted. It was a remnant from his original code, I've addressed it my answer.
kekekela
A: 

I think kekekela's answer is correct, but it seems inefficient due to unnecessary duplication. I'd suggest:

 DateTime date;
 EnumerableRowCollection<DataRow> query = 

 from order in _table.AsEnumerable()
 select 
   new {
        OrderDate = 
          !DateTime.TryParse(Convert.ToString(
              order.Field<DateTime>("OrderDate")), out date)
          ? String.Empty : date.ToShortDateString()
       }

The key here is that TryParse doesn't throw on null or empty.

Steven Sudit
I'd also try it with `ToString` instead of `Convert.ToString`...
Steven Sudit