开发者

DataTable to EnumerableRowCollection

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)

 Enume开发者_运维技巧rableRowCollection<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?


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


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.


Here is a more concise answer.

var badDate = DateTime.Parse("01/01/1999");
var query = 
    from order in _table.AsEnumerable()
    select new {
        OrderDate = (order.Field<DateTime>("OrderDate").Date == badDate.Date) ? String.Empty : date.ToShortDateString()
    };

NOTE: It is not possible to stored "00/00/1999" as a temporal type in a relational database. I think you meant "01/01/1999" to be the sentinel value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜