如何创建一个 if else 语句在 C# 中使用 Linq

发布时间: 2017/2/26 0:09:35
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我创建的 web api 用 linq to 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;
    }
}

解决方法 1:

假设你想要掩盖产品名称,如果 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,
    /*... */
});
赞助商