Reputation: 239
I have a file, a.csv, which contains a square matrix of n by n dimensions, in the following format:
1,2,3
4,5,6
7,8,9
And I want to read it into an int[], something like:
StreamReader csv = new StreamReader("a.csv");
int n = 3
string[] lines = new string[n];
int[] intlines = new int[n]
int q = 0;
bool exiting = false;
do
{
if (csv.ReadLine() != "")
{
exiting = true;
}
if (exiting == false)
{
lines[q] = (((csv.ReadLine()).Split(",")).ToString());
q++;
}
}
while (exiting == false);
Console.WriteLine("Finished Reading!");
System.Threading.Thread.Sleep(500);
int q2 = 0;
foreach (string s in lines)
{
Console.WriteLine("lines: {0}", s);
intlines[q2] = int.Parse(s);
}
foreach (int i in intlines)
{
Console.WriteLine("intlines: {0}", i.ToString());
}
Console.ReadKey();
At the moment, there is something wrong with it as the compiler is going on about char[]'s. Anyways, how would I read the horizontal lines and the vertical lines as well, into a 2 dimensional int[]? Thank you.
Upvotes: 1
Views: 3308
Reputation: 4025
Just other variant from @Malik's answer.
string[] data = File.ReadAllText(@"D:\code\cs\sample.txt")
.Split(new char[] { ',','\r','\n' });
int[] ints = data.Where(x => x.Count() != 0)
.Select(x => int.Parse(x)).ToArray();
foreach(var e in ints)
{
Console.WriteLine(e);
}
Upvotes: 0
Reputation: 12437
Try this:
using (var sr = new StreamReader("a.csv"))
{
var myArray = sr.ReadToEnd()
.Split('\n')
.SelectMany(s => s.Split(',')
.Select(x => int.Parse(x)))
.ToArray<int>();
foreach(var x in myArray)
Console.WriteLine (x);
}
Upvotes: 2
Reputation: 63
You should consider using CSVhelper by Josh Close on nuget and github https://github.com/JoshClose/CsvHelper
it's an excellent library.
Upvotes: 0