0

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));
        }
    }
}
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
Priyank Kapadia
  • 203
  • 4
  • 14
  • Are you running 32 bit or a 64 bit version? – weismat Jul 03 '12 at 08:18
  • possible duplicate of [Why am I getting an Out Of Memory Exception in my C# application?](http://stackoverflow.com/questions/597499/why-am-i-getting-an-out-of-memory-exception-in-my-c-sharp-application) – Mahmoud Gamal Jul 03 '12 at 08:18

2 Answers2

7

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

var l1 = Enumerable.Range(999900000, 1000000000);
foreach(var f in l1)
    Console.WriteLine(f);
Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92
2

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.. 
}
Tigran
  • 61,654
  • 8
  • 86
  • 123