Tuesday, August 9, 2022

[FIXED] Why did I get an exception "Cannot implicitly convert type 'bool' to 'long?'" when using the LINQ Sum method and how to fix it?

Issue

I have the following code which is working:

IEnumerable<Decimal?> values = getValues();

var sum = values.Where(x => x > 0).Sum();

But if I try:

var sum = values.Sum(x => x > 0);

I get the error:

Cannot implicitly convert type 'bool' to 'long?'

Shouldn't this work either applying the filter in Sum or Where?


Solution

Indeed, Sum requires numbers values and not boolean evaluation results.

You need first to filter using Where or Select (not relevant here) then Sum:

var sum = values.Where(x => x != null && x > 0).Sum();

I added the null check because the collection is type of decimal?.

Else you need to write that but this is less speed optimized:

var sum = values.Sum(x => x != null && x > 0 ? x : 0);

Using a selector for Sum is for example usefull when having classes, structs or tuples:

var sum = controls.Sum(control => control.Width);


Answered By - user12031933
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.