PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

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?

 August 09, 2022     c#, decimal, linq, numbers, sum     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing