Lin Aung
Lin Aung

Reputation: 427

Summing integer array

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?

Upvotes: 0

Views: 114

Answers (2)

Salah Akbari
Salah Akbari

Reputation: 39946

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

Upvotes: 7

nemanja228
nemanja228

Reputation: 551

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

Upvotes: 2

Related Questions