0

I have a string array that contains... well, strings, some of which are numbers. I am looking to sum only the numbers from the string, using LINQ.

I came up with this:

        var array = new string[] { "asd", "asd", "53", null, "51", "asd" };
        int sum = array.Where(x => int.TryParse(x, out _)).Select(x => int.Parse(x)).Sum();

However I am wondering if there is a way to, sort of, unite the Where and Select clauses somehow?

Thanks!

2 Answers 2

5

You can not combine Where and Select, but you can change it to parse string only once

var sum = array
    .Select(text => (IsNumber: int.TryParse(text, out var number), Number: number))
    .Where(value => value.IsNumber)
    .Sum(value => value.Number);

Another approach to do everything in the Sum

var sum = array.Sum(text => int.TryParse(text, out var number) ? number : 0);

Actually you can unite the Where and Select clauses, only because you calculating a sum.
For text, which is not valid number return 0.

var sum = array
    .Select(text => { int.TryParse(text, out var number); return number; })
    .Sum();

You can go further and create an extension method for string. Which will make such expressions simpler

public static int ParseOrDefault(string value)
{
    int.TryParse(text, out var number); 
    return number;
}

var sum = array.Sum(value => value.ParseOrDefault());
Sign up to request clarification or add additional context in comments.

Comments

3

In this particular case you can use Aggregate:

array.Aggregate(0, (acc, s) => int.TryParse(s, out var val) ?  acc + val : acc)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.