Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# console app System.StackOverflowException' was thrown on big list/array

I trying to write a simple console app for a friend that want to use it for lottery. The app is working fine on small list but as the list grows, it became slower and finally it throws overflow exception. When the list length is less than 5.000, it works fine.

The app asks for starting ticket number, ending ticket number and winning numbers. Then it takes rnadom numbers of the list and delete them so no dublicates occur.

As i understand, the problem is not the length of the list, but the method that select the number from the list and removes right after.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

You can see the code here:
dotnetfiddle script

The console app is compiled with .net 4.8

>Solution :

Use a loop instead of recursion, and only call .ToList() once for the array

public static int GetNumber(int[] arr) 
{
    return GetNumber(arr.ToList());
}
public static int GetNumber(List<int> list)
{
    while (list.Count > 1)
    {
        //Remove random number from list
        list.RemoveAt(random.Next(0, list.Count));
    }

    return list[0];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading