我正在使用 linq to sql 创建一个 web api。我需要在我的.我在网上找不到任何东西似乎每个人都在使用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),
/*... */
});
可以在赋值时放置条件 conditional operator .
可选地,您可以在实例化对象之前将其存储在变量中:
var productName = oneOrder.ProductName;
if (oneOrder.ProductID == 'A')
{
productName = "Archived Product";
}
results.Add(new CustomerOrderHistory
{
/*...*/,
ProductName = productName,
/*... */
});
关于c# - 如何使用 Linq 在 C# 中创建 if else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37308750/