繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM