我正在努力创建一个' if '下面的编码声明:
var qisg = new QuoteItemSectionGroup
{
SectionGroup = db.SectionGroups.Where(x => x.Name == "Longitudinals" && x.Section == TruckSection.Floor).First(),
StockItem = quoteItem.Chassis.Longitudinal, <<-- Here
Quantity = 2,
Length = globals.FloorCalculatedLength
};
示例:
if (quoteItem.Chassis.Longitudinal == "SCH100")
Stockitem = quoteItem.BodyType.Longitudinal;
我有没有办法在 var qisg 中创建这样的方法?
编辑:这就是代码现在的样子
var qisg = new QuoteItemSectionGroup
{
SectionGroup = db.SectionGroups.Where(x => x.Name == "Longitudinals" && x.Section == TruckSection.Floor).First(),
StockItem = quoteItem.BodyType.Longitudinal == "SCH100" ? quoteItem.Chassis.Longitudinal : quoteItem.BodyType.Longitudinal,
Quantity = 2,
Length = globals.FloorCalculatedLength
};
我收到错误:
运营商&#39; ==&#39;不能应用于类型的操作数 &#39; TrucksWcf.Models.StockItem&#39;和&#39;字符串&#39;
对不起,但有些答案有点太复杂了我无法理解0_o
ALSO 以下是分配给产品的另一个StockItem的示例:
qisg = new QuoteItemSectionGroup
{
SectionGroup = db.SectionGroups.Where(x => x.Name == "Cross Member" && x.Section == TruckSection.Floor).First(),
StockItem = db.StockItems.Where(x => x.StockCode == "SCH075").First(),
Length = globals.FloorCalculatedWidth
};
答案 0 :(得分:4)
您可以使用conditional ternary operator:
?:运算符可用作if ... else语句的快捷方式。 它通常用作
if...else
StockItem = (quoteItem.Chassis.Longitudinal == "SCH100" ? quoteItem.BodyType.Longitudinal : null),
的更大表达式的一部分 声明会很尴尬。
test ? expression1 : expression2
表达式的格式,解释如下:
karma-coverage
答案 1 :(得分:4)
正如其他人所说的那样,条件运算符是完美的,如果它是一个简单的,如果这......那么......否则是别的场景。
如果您的条件更复杂,您可以创建一个检查条件并返回适当值的方法。所以......就像......
var qisg = new QuoteItemSectionGroup
{
SectionGroup = db.SectionGroups.Where(somecondition).First(),
StockItem = DetermineStockItem(valueToCheck)
Quantity = 2,
Length = globals.FloorCalculatedLength
};
public StockItem DetermineStockItem(object param)
{
// Include complex if and logic here.
return SomeStockItem;
}
修改:我刚看到您的更新并显示错误消息。看起来quoteItem.BodyType.Longitudinal
的类型为StockItem
。鉴于您的上一个代码段显示StockItem
有StockCode
我认为您可能需要这样的内容......
var qisg = new QuoteItemSectionGroup
{
SectionGroup = db.SectionGroups.Where(x => x.Name == "Longitudinals" && x.Section == TruckSection.Floor).First(),
StockItem = quoteItem.BodyType.Longitudinal.StockCode == "SCH100" ? quoteItem.Chassis.Longitudinal : quoteItem.BodyType.Longitudinal,
Quantity = 2,
Length = globals.FloorCalculatedLength
};
答案 2 :(得分:2)
尝试使用条件运算符(https://msdn.microsoft.com/en-us/library/ty67wk28.aspx):
StockItem = quoteItem.Chassis.Longitudinal == "SCH100" ? quoteItem.BodyType.Longitudinal : null,
答案 3 :(得分:2)
var qisg = new QuoteItemSectionGroup
{
SectionGroup = db.SectionGroups.Where(x => x.Name == "Longitudinals" && x.Section == TruckSection.Floor).First(),
StockItem = (quoteItem.Chassis.Longitudinal == "SCH100" ? Stockitem = quoteItem.BodyType.Longitudinal : String.Empty),
Quantity = 2,
Length = globals.FloorCalculatedLength
};