是否有可能在LINQ中创建三种不同的条件,并有三种不同的结果?

时间:2018-03-06 09:47:39

标签: c# linq

以下是我的Lambda LINQ。

return await _trialBalanceContext
    .Entries
    .Select(x => new
    {
        accountTitle = x.AccountTitle,
        debitAmount = x.DebitAmount,
        creditAmount = x.CreditAmount,
    })
    .ToListAsync();

我想在上面的LINQ中应用以下条件。

if (accountTitle == "Asset"){
    debitAmount = debitAmount * 100
    creditAmount = creditAmount * 100
 } else if (accountTitle == "Expense"){
    debitAmount = debitAmount - creditAmount
    creditAmount = creditAmount * debitAmount
 } else 
 {
    debitAmount = creditAmount + 30
    creditAmount = debitAmount + 50
 }

1 个答案:

答案 0 :(得分:2)

你可以这样做:

return await _trialBalanceContext
    .Entries
    .Select(x => new
    {
        accountTitle = x.AccountTitle,
        debitAmount = (x.AccountTitle == "Asset") ? x.DebitAmount*100 : ((x.AccountTitle == "Expense") ? x.DebitAmount - x.CreditAmount : x.CreditAmount + 30),
        creditAmount = (x.AccountTitle == "Asset") ? x.CreditAmount*100 : ((x.AccountTitle == "Expense") ? x.CreditAmount * x.DebitAmount : x.DebitAmount + 50),
    })
    .ToListAsync();