在变量中正确使用“if语句”

时间:2015-06-10 11:40:45

标签: c# linq-to-entities entity-framework-6

我想使用下面的 if语句来计算我的产品的StockCode,但是我收到错误:

  

无法将类型'TruckWcf.Models.StockItem'隐式转换为'bool'

现在我是C#和EF6的新手,所以我尽力了解这里发生了什么:P。

 var qisg = new QuoteItemSectionGroup
        {
            SectionGroup = db.SectionGroups.Where(x => x.Name == "Longitudinals" && x.Section == TruckSection.Floor).First(),
            StockItem = db.StockItems.Where(x => x.StockCode == "SCH113").First() ? quoteItem.Chassis.Longitudinal : quoteItem.BodyType.Longitudinal, // <<-- Here lies my error
            Quantity = 2,
            Length = globals.FloorCalculatedLength
        };

有人可以告诉我如何解决这个小而简单的问题。谢谢!

4 个答案:

答案 0 :(得分:1)

As explained to you in your previous question on this topic,三元运算符采用以下形式:

 <ion-content class="has-subheader" ng-controller="myCtrl">
      <ion-list>
        <ion-item ng-repeat='item in posts' class="item-thumbnail-left item-text-wrap">
          <img src="http://placehold.it/100x100" alt="photo">
          <h2>{{post.title}}</h2>
          <h4>Place</h4>
          <p style="font-size:12px; line-height:16px;">Quisque quis sem a velit placerat vehicula quis nec felis. Mauris posuere, nisl vitae condimentum luctus, tellus enim blandit orci, quis efficitur nibh libero eget dui. Aliquam fermentum velit quis sem molestie.</p>

        </ion-item>
      </ion-list> 
    </ion-content>

但你正在做:

<script type="text/javascript">
    function pageLoad(sender, args) {
        if (args.get_isPartialLoad()) {
            $(function () {
                initializer();
            });
        }
    }
</script>

在这种情况下,var x = <some boolean expression> ? <value assigned to x if true> : <value if false> 不会返回布尔值。因此,您需要修复此表达式,可能是通过将其与其他值进行比较。

答案 1 :(得分:1)

如果我正确理解了这个问题,你需要这样的东西:

StockItem = db.StockItems.Any(x => x.StockCode == "SCH113")
? quoteItem.Chassis.Longitudinal
: quoteItem.BodyType.Longitudinal

答案 2 :(得分:0)

只需使用?? operator选择值即可。这基本上是说取??之前的第一个值,但如果它为null,则返回之后的值。也可以使用FirstOrDefault,否则您可能会获得异常而不是null返回值。最后删除Where,因为这样写的更简单(@YuvalItzchakov的好地方):

var qisg = new QuoteItemSectionGroup
{
    SectionGroup = db.SectionGroups.Where(x => x.Name == "Longitudinals" && x.Section == TruckSection.Floor).First(),
    StockItem = 
        db.StockItems.FirstOrDefault(x => x.StockCode == "SCH113") ?? 
            quoteItem.Chassis.Longitudinal
    Quantity = 2,
    Length = globals.FloorCalculatedLength
};

答案 3 :(得分:0)

First()将返回一个对象而不是一个布尔表达式,这就是你需要的。所以你必须做出这样的改变:

更改此行代码:

StockItem = db.StockItems.Where(x => x.StockCode == "SCH113").First() ? quoteItem.Chassis.Longitudinal : quoteItem.BodyType.Longitudinal

对此:

StockItem = db.StockItems.Where(x => x.StockCode == "SCH113").First() == null ? quoteItem.Chassis.Longitudinal : quoteItem.BodyType.Longitudinal

现在,这只是一个描述您必须在此处进行的类型更改的示例。我在这里使用了null。您也可以使用First().SomeField == somevalue或类似的东西。只要确保它是一个布尔条件,你就可以了。

希望这有帮助。

相关问题