简短"如果"声明没有"否则"

时间:2018-01-16 12:42:31

标签: c# if-statement linq-to-entities

我有一个班级:

public class DriverShortInfoElement
{
    ......
    public DateTime? VistracksDateAdded { get; set; }
}

我希望用来自DbContext的数据来填充它。我想填充VistracksDateAdded只有一些条件为真,否则保留为null:

我试着这样:

var list = (from i in _db.Drivers
            select new DriverShortInfoElement()
            {
                .....
                VistracksDateAdded = (i.ProblemSyncToVistracksDriver != null) ? i.ProblemSyncToVistracksDriver.DateAdded : null
            }).ToList();

但编译错误。怎么做这个简单的事情?

3 个答案:

答案 0 :(得分:3)

我猜DateAddedDateTime。如果您使用条件运算符,则必须将null强制转换为DateTime?或使用new Nullable<DateTime>(),因为nullDateTime之间不存在隐式转换:

VistracksDateAdded = i.ProblemSyncToVistracksDriver != null
    ? i.ProblemSyncToVistracksDriver.DateAdded 
    : new Nullable<DateTime>()

答案 1 :(得分:3)

还有另一个运营商:Null conditional operator

VistracksDateAdded = i.ProblemSyncToVistracksDriver?.DateAdded

答案 2 :(得分:-1)

var query =
    from driver in _db.Drivers
    select new DriverShortInfoElement
    {
        VistracksDateAdded = driver.ProblemSyncToVistracksDriver != null
            ? driver.ProblemSyncToVistracksDriver.DateAdded
            : default(DateTime?)
    };