简体   繁体   中英

Sum any strings that are numbers from string array using LINQ

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!

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());

In this particular case you can use Aggregate :

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

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