将c#foreach转换为Linq表达式

时间:2016-06-12 11:06:35

标签: c# linq

我在c#中有以下代码片段正常工作

foreach (var customer in customers.OrderBy(x => x.CustomerId))
{
    if (customer.CustomerId != customerId)
    {
        winningRate = Helper.Utility.WinningRate(settledCustomers, customer.CustomerId).Status;
        numberOfBets = customers.Count(x => x.CustomerId == customer.CustomerId);
        numberOfWinnings = customers.Count(x => x.CustomerId == customer.CustomerId && x.Win > 0);
        averageBet = Helper.Utility.CustomerAverageBet(settledCustomers, customer.CustomerId);
    }

    var risky = Helper.Utility.CheckRiskyBet(winningRate, numberOfWinnings, numberOfBets, averageBet, customer.Stake, customer.Win);

    customer.Status = risky.Status;
    customer.Message = risky.Message;
    customerId = customer.CustomerId;
}
return customers;

现在我想将上面的代码转换为LINQ表达式,并且我已经编写了下面的代码,它没有提供与

相同的输出
var r = from c in customers
        let winningRate1 = Helper.Utility.WinningRate(settledCustomers, c.CustomerId).Status
        let numberOfBets1 = customers.Count(x => x.CustomerId == c.CustomerId)
        let numberOfWinnings1 = customers.Count(x => x.CustomerId == c.CustomerId && x.Win > 0)
        let averageBet1 = Helper.Utility.CustomerAverageBet(settledCustomers, c.CustomerId)
        let risky1 = Helper.Utility.CheckRiskyBet(winningRate, numberOfWinnings, numberOfBets, averageBet, c.Stake, c.Win)
        where c.CustomerId != customerId
        orderby c.CustomerId
        select new Customer
        {
            Status = risky1.Status,
            Message = risky1.Message,
            CustomerId = c.CustomerId
        };

1 个答案:

答案 0 :(得分:0)

     where c.CustomerId != customerId

这显然是错误的,因为它减少了循环运行的次数。

在转换为查询表达式时,许多让循环中的子句和控制流变得丑陋。多语句lambda通常更容易,并为您提供相同的功能代码优势:

customers
.OrderBy(x => x.CustomerId)
.Select(c => {
    if (customer.CustomerId != customerId)
    {
        winningRate = Helper.Utility.WinningRate(settledCustomers, customer.CustomerId).Status;
        numberOfBets = customers.Count(x => x.CustomerId == customer.CustomerId);
        numberOfWinnings = customers.Count(x => x.CustomerId == customer.CustomerId && x.Win > 0);
        averageBet = Helper.Utility.CustomerAverageBet(settledCustomers, customer.CustomerId);
    }

    var risky = Helper.Utility.CheckRiskyBet(winningRate, numberOfWinnings, numberOfBets, averageBet, customer.Stake, customer.Win);

    return new Customer
        {
            Status = risky.Status,
            Message = risky.Message,
            CustomerId = c.CustomerId
        };
});

此代码只是一个草图,它有一些您可以轻松修复的问题。例如,我分配给非局部变量。你的代码没有解释那些是什么,所以我让他们独自一人。