Priyank Kapadia
Priyank Kapadia

Reputation: 203

Out of memory exception C# List

How should I make a list which can accommodate this range(in the code) since it is showing out of memory exception?

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var l1 = Enumerable.Range(999900000, 1000000000).ToList();
            l1.ForEach(f => Console.WriteLine(f));
        }
    }
}

Upvotes: 0

Views: 4057

Answers (2)

Tigran
Tigran

Reputation: 62246

Do not collect all data you need in the list especially if you know already the content of it, but use enumerator, to reduce in this way memory footprint of your app.

For example:

    IEnumerable<int> GetNextInt()
    {
        for(int i=999900000; i< 1000000000; i++)
        {
            yield return i;
        }
    }

and use this after in loop like

foreach(var integer in GetNextInt())
{ 
    //do something.. 
}

Upvotes: 2

Eren Ers&#246;nmez
Eren Ers&#246;nmez

Reputation: 39085

Don't convert to List<T>, just enumerate:

var l1 = Enumerable.Range(999900000, 1000000000);
foreach(var f in l1)
    Console.WriteLine(f);

Upvotes: 7

Related Questions