【发布时间】:2015-08-20 08:28:51
【问题描述】:
上面的标题是我可以尝试提出问题的最佳方式,如果在您阅读了下面的问题后标题不正确,我们深表歉意。 :)
所以,我得到了下面的编码,我从另一个表中获得的信息将数据添加到我的数据表中的某些列。这几乎就像 Excel 中的 VLOOKUP。
var qisg = new QuoteItemSectionGroup
{
SectionGroup = db.SectionGroups.Where(x => x.Name == "Ali Bottom Rail" && x.Section == TruckSection.FrontEndRequirments).First(),
//StockItem is set here
StockItem = quoteItem.BodyType.Name == "Royal Corrugated" || quoteItem.BodyType.Name == "Royal Smooth Riveted" ? db.StockItems.Where(x => x.StockCode == "AEX165").First() : null,
};
qisg.Quantity = qisg.StockItem == null ? 0 : 1;
qisg.Weight = Math.Round(((double)qisg.Length * (double)qisg.Quantity) * (double)qisg.StockItem.Mass, 2);
qisg.Cost = Math.Round(((double)qisg.Length * (double)qisg.Quantity) * (double)qisg.StockItem.UnitCost, 2);
quoteItem.SectionGroups.Add(qisg);
如您所见,我在哪里设置了StockItem,我说:如果 BodyType = Royal Corrugated 那么StockItem 代码应该是AEX165 else 股票代码应为null。我从 StockCode 中获得所有我需要的数量、重量和成本信息,就像 VLOOKUP 一样。
现在我的大问题是,当我在StockItem 中将 else 设置为 null 时,我将无法从我的数据表中获取任何信息,除了我手动设置的SectionGroup。因此,当 StockItem 为 null 时,我希望能够跳过整个 var qisg 并且不将数据添加到我的数据表中。
如果我不能跳过var qisg,它会抛出以下错误:
对象引用未设置为对象的实例。
在下面的编码中:
foreach (var sectionGroup in quote.Items.First().SectionGroups)
bills.Add(new ListOfBills
{
Cost = sectionGroup.Cost,
PricePerMeter = sectionGroup.Price_m,
GroupName = sectionGroup.SectionGroup.Name,
Length = sectionGroup.Length,
Quantity = sectionGroup.Quantity,
StockCode = sectionGroup.StockItem.StockCode,
StockDescription = sectionGroup.StockItem.Description,
TruckSection = sectionGroup.SectionGroup.Section,
Weight = sectionGroup.Weight,
Width = sectionGroup.Width
});
return bills;
所以如果StockItem 为null,我真的需要知道如何跳过该变量。任何帮助或建议真的很棒!很抱歉,我不知道某些对象和类型的所有正确技术术语是 c#,所以请略过它,如果您需要更多信息,请随时询问。 :)
【问题讨论】: