-2

I have an LINQ Expression which converts the Dateformat from UTC to the date format of the User Culture.

for (int i = 0; i < datexml.count ; i++)
{
    if (datatype.ToLower() == "date")
    {  
        myList.Select(c => { ((object[])(c))[i] =    ConvertFromUTCDate( Convert.ToDateTime (((object[])(c))[i]),  UserTimeZone); return c; }).ToList();
    }
}

Some times the date value in (object[])(c))[i] could be null or have string or decimal if the value is wrongly stored in DB.

How do I check if the values is not null and has date and then convert it in this expression.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Algi
  • 195
  • 1
  • 2
  • 11
  • I think by trying to use linq you have made the job alot harder for yourself, you would be better just doing a non-linq alternative that allows you to error handle appropriately and easily understood – Sayse Jul 02 '15 at 06:16
  • Can you show us the type of `myList` ? – Mivaweb Jul 02 '15 at 06:16
  • Also, You [shouldn't](http://stackoverflow.com/q/1660192/1324033) really compare strings with `ToLower` – Sayse Jul 02 '15 at 06:16
  • 1
    And what *is* the type of `c`? (What is the type of `myList`?) All those brackets are hurting my eyes... it would really help if you'd provide a short but complete program demonstrating the problem. We don't know what `ConvertFromUTCDate` is, either - or why you're calling `Select` and then `ToList` and ignoring the result. Basically, the code here makes very little sense in its current form. – Jon Skeet Jul 02 '15 at 06:16
  • ConvertFromUTCDate is a static function which converts the UTC date to user culture date and myList is of type object (myList = DataList.OfType().ToList();) – Algi Jul 02 '15 at 06:19
  • is this work? : `myList.Where(/* filter c here */).Select(...)` – Cologler Jul 02 '15 at 06:20

1 Answers1

3

To avoid adding more complexity and being able to read and maintain the code easily, extract the anonymous method and make it a named method

from

c => { ((object[])(c))[i] = ConvertFromUTCDate( Convert.ToDateTime (((object[])(c))[i]), UserTimeZone); return c; }

to

public DateTime ConvertFromObjectToDate(object dbdate){
    if(dbdate is null || !(dbdate is DateTime))return DateTime.MinValue;
     var result =   ConvertFromUTCDate(Convert.ToDateTime (dbdate),UserTimeZone); 
     return result; 
}

and

c => {((object[])(c))[i] =  ConvertFromObjectToDate(((object[])(c))[i]);}
n00b
  • 1,832
  • 14
  • 25
  • 1
    Also you can use `myList.Cast().Select(c=>ConvertFromObjectToDate(c[i]))` – Alexey Nis Jul 02 '15 at 06:28
  • 1
    In OP's horrible linq, it also set the value to the `((object[])(c))[i]`.. – Eric Jul 02 '15 at 06:29
  • Fixed that @Eric. Actually I was just trying to demonstrate plain old method can be better than Linq+Anonyous Method. Not actually give a fully working solution... – n00b Jul 02 '15 at 06:32