简体   繁体   中英

lambda expression to simple c#

Hi i am trying to correct a code and I got stuck at a lambda expression.

addrow.Outcome1 = values.Where(row => DecompRowComparer(row, filterstring1))
                        .ToList()
                        .Sum(row => Convert.ToDouble(row[outcomeIndex]));

Can any help me to translate this expression into a simple c# code.

I want to check if row[outcomeIndex] has only only one letter or not, if it has only one letter and it is a.(dot) then I want to replace it with 0, but I am not sure how to do this

row[outcomeIndex] can be numeric as well as a.(dot) and this line give error: Input string was not in a correct format. when the row[outcomeIndex] is a.(dot), so how can I convert this line into simple way (multilines)

Here's the code without using Linq

double sum = 0;
foreach(var row in values)
{
    if(DecompRowComparer(row, filterstring1))
    {
        sum += Convert.ToDouble(row[outcomeIndex])
    }
}

addrow.Outcome1 = sum;

This is simple LINQ code. Converting it into a loop would be a lot more complex. ToList() is redundant here as Sum works with any IEnumerable.

Instead of using Convert.ToDouble use double.TryParse which allows you control what happens if parsing fails.

double.TryParse returns true if it succeeds, false otherwise. The parsed double is returned as an out variable. You can combine that with the ternary operator to return the parsed value on success, or 0, or any other default value on failure.

The ternary operator (condition)? trueExpression:falseExpression (condition)? trueExpression:falseExpression checks the condition and returns the result of trueExpression if the condition is true, falseExpression if false.

Putting both together:

var value=double.TryParse(someString,out var result) ? result : 0;

If someString is 13 parsing succeeds and result is set to 13 . If it contains . , parsing fails and the second branch of the ?: expression returns 0;

The query can be rewritten as:

addrow.Outcome1 = values.Where(row => DecompRowComparer(row, filterstring1))
                        .Sum(row=>double.TryParse(row[outcomeIndex],out var d)?d:0)

or

addrow.Outcome1 = values.Where(row => DecompRowComparer(row, filterstring1))
                        .Select(row=>row[outcomeIndex])
                        .Sum(input=>double.TryParse(input,out var d)?d:0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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