在Linq to Entities查询中编写if else

时间:2016-07-02 04:25:44

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

我写了以下代码来计算引用Document到:

var currentStationId = GetCurrentStation();
var result = dbContext
            .Documents
            .Select(x=> 
                    new MyDTO{
                            ...,
                            ReferCounts = x.DocumentStationHistories
                                           .Count(t => t.ToStationId == currentStationId))
                             }

现在我想改变计算ReferCounts

的机制
if(currentStationId == 1) ReferCounts = x.DocumentStationHistories
                                         .Count(t => t.ToStationId == currentStationId &&
                                                     t.FromStationId != t.ToStationId))
else
    ReferCounts = x.DocumentStationHistories
                   .Count(t => t.ToStationId == currentStationId))

如何在我的linq实体查询中使用此代码?

1 个答案:

答案 0 :(得分:0)

以下是ternary if语法的示例。

var result = dbContext
        .Documents
        .Select(x=> 
                new MyDTO{
                        ...,
                        ReferCounts = (currentStationId == 1) ?
                             x.DocumentStationHistories.Count(t => t.ToStationId == currentStationId && t.FromStationId != t.ToStationId)) 
                           : x.DocumentStationHistories.Count(t => t.ToStationId == currentStationId))
                         }