XelaGreb
XelaGreb

Reputation: 61

Accumulate values in C#

I'm trying to replicate a simple action of accumulating a value a n-th amount of times. So something like value 4 take 10 times would be: [0,4,8,12,16,20,24,28,32,36]. What am I doing wrong?

        public static IList SumValues(int value, int times)
        {
            List<object> sums = new List<object>();
            for (int i = 0; i < times; i = i + 1)
            {
                while (i < times)
                    sums.Add(value);
            }
            return sums;
        }

Upvotes: -1

Views: 2319

Answers (5)

agentt015
agentt015

Reputation: 33

I am not really sure, but try using sums.Add(value * i); instead of your sums.Add(value);

Tip: in your for cycle use i++ instead of i = i + 1. It is more common and also faster to type.

Upvotes: 0

maccettura
maccettura

Reputation: 10818

I don't know why you are creating a list of object when its very clearly int 's in the list. I have changed the code to return an IEnumerable<int> so you can iterate without materializing. With that in mind you can make your code a bit shorter:

public static IEnumerable<int> SumValues(int initialValue, int iterations)
{
    for(int i = 0; i < iterations; i++)
    {
        yield return initialValue * i;
    }       
}

If you need it in a List<T> or an Array you can just call the appropriate method (.ToList() or .ToArray()):

List<int> someIntList = SumValues(4, 10).ToList();
int[] someIntArray = SumValues(4, 10).ToArray();

Fiddle here

Upvotes: 3

Dortimer
Dortimer

Reputation: 617

public static IList SumValues(int value, int times) // you need to define the type for the return list
{
    List<object> sums = new List<object>(); // you could probably use List<int> here instead of object, unless there's some logic outside of this function that treats them as objects
    int incrementedValue = 0;
    for (int i = 0; i < times; i++) // i++ is the same as i = i+1, but a little cleaner
    {
        sums.Add(incrementedValue);
        incrementedValue += value;
    }

    return sums;
}

This will always include '0' in the list

Upvotes: 0

Ljubomir Bacovic
Ljubomir Bacovic

Reputation: 584

Try this:

public static IList SumValues(int value, int times)
{
   List<int> sums = new List<int>();
   for (int i = 0; i < times; i++)
   {
       sums.Add(i*value);
   }
   return sums;
}

Upvotes: 1

Guvante
Guvante

Reputation: 19203

You are not changing the value of value so it will always be the original. Add appends the item to the end of the list.

Upvotes: 0

Related Questions