2017-06-20 57 views
1

我想檢查lastlogindate列是否爲null。如果它不爲空,我想將對象轉換爲日期時間格式,否則我想返回null作爲條件運算符或linq。如何處理數據表列值是

public class UserBase { public string UserName {get;組; }

public string FirstName { get; set; } 

    public string LastName { get; set; } 

    public string Email { get; set; } 

    public string PhoneNo { get; set; } 

    public string MobilePhone { get; set; } 

    public string GroupName { get; set; } 

    public DateTime LastLogOnDate { get; set; } 

    public string Active { get; set; } 

    public string PlantId { get; set; } 

    public string UserId { get; set; } 
} 

上面是我的課堂和方法

user = datatable.AsEnumerable().Select(row => 
        new EGDataStructure.UserBase 
        { 
         UserName = row.Field<string>("User Name"), 
         FirstName = row.Field<string>("First Name"), 
         LastName = row.Field<string>("Last Name"), 
         Email = row.Field<string>("Email ID"), 
         PhoneNo = row.Field<string>("Phone No"), 
         MobilePhone = row.Field<string>("Mobile No"), 
         GroupName = row.Field<string>("Group Name"), 
         LastLoginDate=row.Field<DateTime>("Last Logged Date") 
         LastLogOnDate = if (LastLoginDate != DBNull.Value)??Convert.ToDateTime(row.Field<DateTime>("Last Logged Date"),CultureInfo.InvariantCulture):Null, 

         Active = row.Field<string>("active"), 
         UserId = row.Field<string>("userId") 
        }).ToList(); 
       } 
+0

LastLoginDate =行.Field (「Last Logged Date」)== null? null:Convert.TodateTime(row.Field (「Last Logged Date」))...你試過這個嗎? –

+0

請嘗試@AnkeshKumar提及的內容,因爲您無法引用其他變量,例如'New {'語句'if(LastLoginDate!= DBNull.Value)'中的'LastLoginDate'。 –

+0

雅我試過,但我越來越類型的條件表達式無法確定,因爲沒有和system.Datetime – suganya

回答

1

DateTime是一個結構,所以你會需要Nullable<DateTime>(或簡短DateTime?)。

public DateTime? LastLogOnDate { get; set; } 

LastLogOnDate = row.Field<DateTime?>("Last Logged Date") 

在要null和其他值之間明確地分辨的情況下,例如,因爲該領域是原來的字符串,需要轉換:

LastLogOnDate = row.IsNull("Last Logged Date") 
    ? (DateTime?)null 
    : Convert.ToDateTime(row.Field<string>("Last Logged Date"), CultureInfo.InvariantCulture))