Adding two numbers together and then adding it to an array.


  • Hello, I got a little program that generates two random numbers, it then adds them together.

    I want to add this sum to the array, but when the program runs another loop and the sum is different then add it again but don't delete the first one. Is this possible?

    Friday, April 21, 2017 10:49 PM

All replies

  • You should use List<T> e.g. List<int> which permits add, remove and change. If you need an array rather than a list later you can use .ToArray() or the List<T>. You can use Sum for instance to get just that.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Saturday, April 22, 2017 12:55 AM
  • Are you keeping track of the array element you need to update? If not, then that is most likely your problem.

    That being said, I think you should look into using a Dictionary - which will allow you to update a Dictionary item based on a key.

    So your Dictionary may look like:

    var randomNumbers = new Dictionary<string, int>();

    And you would set it like:

    randomNumbers.Add("SomeNumber", 2);

    Then update like:

    randomNumbers["SomeNumber"] = 3;

    More on Dictionary here:

    william xifaras

    Saturday, April 22, 2017 2:19 PM
  • Hi IHaveNoIdeaWhatIAmDoing12,

    Thank you for posting here.

    For your question, please try the following code.

       List<List<int>> list = new List<List<int>>();
                var rand = new Random();
                for (int i = 0; i < 10; i++)
                    List<int> sublist = new List<int>();               
                    for (int v = 0; v < 2; v++)
                        sublist.Add(rand.Next(11, 21));

    Do you mean you want to add the sum to the sublist at the end of the two random numbers? You could add it when you add the sublist. Or you could do a loop, foreach the list, add it to the sublist.

    If I misunderstanding what you want, please feel free to contact us.

    Best Regards,


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Tuesday, April 25, 2017 8:33 AM