Rafal Niedzielak
Rafal Niedzielak

Reputation: 1

Wrong results for suming right side of List

During my exercises I receiving wrong Sum() for piece of code like below:

int right = arr.Where(v => arr.IndexOf(v) > i).Sum();

Can anyone explain me why this doesn't work? Example: List like this: {1, 2, 3, 3} for i = 2 for left side:

int left = arr.Where(v => arr.IndexOf(v) < i).Sum();

returned 3, but for right side of list Sum()=0 Why?

Upvotes: 0

Views: 71

Answers (4)

hessam hedieh
hessam hedieh

Reputation: 820

Note that IndexOf returns the index of first occurrence of the element.
The problem is with your input list, in that you have two 3s, so whenever the IndexOf(3) is evaluated the index returned is 2, with condition index > 2 obviously it is ignored.

Upvotes: 7

Ondřej Kub&#237;ček
Ondřej Kub&#237;ček

Reputation: 247

If you want to know sums of left and right sides. The best would be to use .Skip() and .Take() because index of will return index of first occurence in the collection.

int right = arr.Skip(i).Sum();
int left = arr.Take(i).Sum(); // including the i-th element

For this case, the left would be 1+2=3 and right 3+3=6.

Upvotes: 0

Hans Kesting
Hans Kesting

Reputation: 39329

To use the actual index, there is a different overload of Where that also uses the index.

An example from the linked page:

int[] numbers = { 0, 30, 20, 15, 90, 85, 40, 75 };

IEnumerable<int> query =
    numbers.Where((number, index) => number <= index * 10);

foreach (int number in query)
{
    Console.WriteLine(number);
}
/*
 This code produces the following output:

 0
 20
 15
 40
*/

Upvotes: 1

Wojciech Rak
Wojciech Rak

Reputation: 600

I figured out this, problem is in statement

arr.IndexOf(v)

because v = 3 two times and its return 2 both times. For you better to increment the index in loop or something like this.

Upvotes: 0

Related Questions