tags:

views:

76

answers:

3

I have a file of integers. the first number - the number of subsequent numbers. as the easiest way to take this file into an array? C#

Example 1: 8 1 2 3 4 5 6 7 8

Example 2: 4 1 2 3 0

Example 3: 3 0 0 1

+8  A: 
int[] numbers = File
    .ReadAllText("test.txt")
    .Split(' ')
    .Select(int.Parse)
    .Skip(1)
    .ToArray();

or if you have a number per line:

int[] numbers = File
    .ReadAllLines("test.txt")
    .Select(int.Parse)
    .Skip(1)
    .ToArray();
Darin Dimitrov
That is awesome.
Snake
This also includes the 'amount' of numbers per line in the array.
Rob van Groenewoud
@Rob, good remark, updated my answer.
Darin Dimitrov
Nice and clean, I like it. Be aware that it's not compatible with older .Net framework versions though.
Rob van Groenewoud
+1  A: 
int[] numbers = File
    .ReadAllLines("test.txt")
    .First()
    .Split(" ")
    .Skip(1)
    .Select(int.Parse)
    .ToArray();
VirtualBlackFox
A: 

if your file consist of all numbers in column style (under eachother), than you can read it like this

static void Main()
{
    //
    // Read in a file line-by-line, and store it all in a List.
    //
    List<int> list = new List<int>();
    using (StreamReader reader = new StreamReader("file.txt"))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            list.Add(Convert.ToInt16(line)); // Add to list.
            Console.WriteLine(line); // Write to console.
        }
    }
    int[] numbers = list.toArray();
}

ok, post was updated after i posted this, but might be of some help though :)

djerry
thank you very much!
Alexry