-1

I have a text file that looks like this

1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100

in a 10 x 10 grid. using c# I need to take the text file and turn it into a 2d array of integers so that I can manipulate the integers on an independent level. Please help cant work it out,

3
  • To be helped you should post what you have tried and what problem you have. Just asking people for code without effort is not welcomed on this site Commented Dec 5, 2012 at 14:10
  • you need to show what youve done so far - if nothing, then what you intend to do! Commented Dec 5, 2012 at 14:10
  • I do aplogise I am new to the site but will bare it in mind for future references Commented Dec 5, 2012 at 15:16

3 Answers 3

9
String input = File.ReadAllText( @"c:\myfile.txt" );

int i = 0, j = 0;
int[,] result = new int[10, 10];
foreach (var row in input.Split('\n'))
{
    j = 0;
    foreach (var col in row.Trim().Split(' '))
    {
        result[i, j] = int.Parse(col.Trim());
        j++;
    }
    i++;
}

The indices will be 0-based so if you want to access 10th column in fourth row:

Console.WriteLine(result[3,9]); //40
Sign up to request clarification or add additional context in comments.

Comments

8

A jagged array?

int[][] list = File.ReadAllLines("a.txt")
                   .Select(l => l.Split(' ').Select(i => int.Parse(i)).ToArray())
                   .ToArray();

EDIT

You can use JaggedToMultidimensional here

int[,] list2 = JaggedToMultidimensional(list);

4 Comments

Thanks for the quick reply, it has to be a 2d array, cant get my head around it
whats the using directive for it?>
sorted it now, Thanks for all you help
What's going on inthis code?
2

Perhaps:

var result = File.ReadLines(path)
    .SelectMany((l, i) => l.Split()
                           .Select(s => new int[] { i, int.Parse(s) })
                           .ToArray())
    .ToArray();

Edit: Although this is a jagged array int[][].

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.