[英]How to create an if else statement in C# with Linq
我正在用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;
}
}
假設你想掩蓋產品名稱,如果oneOrder.ProductID == 'A'
......
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,
/*... */
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.