我正在用linq创建一个web api到sql。我需要在我的内容中添加一个if语句。我无法在网上找到任何东西似乎每个人都在使用entityframework。
public List<customerorderhistory> GetCustomerOrderHistory(string customerID)
{
try
{
List<customerorderhistory> results = new List<customerorderhistory>();
NorthwindDataContext dc = new NorthwindDataContext();
foreach (CustOrderHistResult oneOrder in dc.CustOrderHist(customerID))
{
results.Add(new CustomerOrderHistory()
{
ProductName = oneOrder.ProductName,
Total = oneOrder.Total ?? 0
});
}
return results;
}
catch (Exception ex)
{
// Return any exception messages back to the Response header
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
response.StatusDescription = ex.Message.Replace("\r\n", "");
return null;
}
}
他就是我所尝试过的。我想我可能会把if语句放在错误的地方。任何帮助将不胜感激。
public List<customerorderhistory> GetCustomerOrderHistory(string customerID)
{
try
{
List<customerorderhistory> results = new List<customerorderhistory>();
NorthwindDataContext dc = new NorthwindDataContext();
foreach (CustOrderHistResult oneOrder in dc.CustOrderHist(customerID))
{
results.Add(new CustomerOrderHistory()
{
if (oneOrder.RecordID == 'A')
{
ProductName = "Archived Product"
}
else
{
ProductName = oneOrder.ProductName,
}
Total = oneOrder.Total ?? 0
});
}
return results;
}
catch (Exception ex)
{
// Return any exception messages back to the Response header
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
response.StatusDescription = ex.Message.Replace("\r\n", "");
return null;
}
}
答案 0 :(得分:3)
假设您想要results.Add(new CustomerOrderHistory
{
/*...*/,
ProductName = (oneOrder.RecordID == 'A' ? "Archived Product" : oneOrder.ProductName),
/*... */
});
...
var productName = oneOrder.ProductName;
if (oneOrder.ProductID == 'A')
{
productName = "Archived Product";
}
results.Add(new CustomerOrderHistory
{
/*...*/,
ProductName = productName,
/*... */
});
使用conditional operator分配时可以放置条件。
或者,您可以在实例化对象之前将其存储在变量中:
<div *ngFor="let item of items"> // let instead of #