0

I have the following code

int[] array = new int[10] { 4, 50 , 60 , 80 , 120 , 46 , 52 , 60 , 18 , 221};


var sum = (from num in array
           where ((num % 4) != 0 && (num % 6 ) != 0) && ((num % 2) != 0)
           select array);

Console.Write(sum.Sum());

The problem is I can't use Sum(). It said

'System.Collections.Generic.IEnumerable' does not contain a definition for 'Sum' and the best extension method overload 'System.Linq.Queryable.Sum(System.Linq.IQueryable)'

How can I get this done?

1
  • Yes I added using System.Linq already. Commented Nov 29, 2018 at 6:52

2 Answers 2

7

Change your code from this:

var sum = (from num in array
    where ((num % 4) != 0 && (num % 6 ) != 0) && ((num % 2) != 0)
    select array);

To this:

 var sum = (from num in array
            where ((num % 4) != 0 && (num % 6) != 0) && ((num % 2) != 0)
            select num);

You need to select num instead of select array. Read more https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=netframework-4.7.2

Sign up to request clarification or add additional context in comments.

Comments

2

From the error message you get,

'System.Collections.Generic.IEnumerable' does not contain a definition for 'Sum' and the best extension method overload 'System.Linq.Queryable.Sum(System.Linq.IQueryable)'

it's observable that the type of your variable num is IEnumerable<int[]>, instead of IEnumerable<int> that you probably expect. You can solve this by changing your code to select num instead of select array.

Also, I would recommend using the fluent extension methods here, so you don't mix two styles in the same place. It's generally good practice to keep your formatting and style consistent. It would look like this:

var sum = array
    .Where(num => num%4 != 0 && num%6 != 0 && num%2 != 0 )
    .Sum();

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.