I\'m trying to read a text file which contains numbers separated by a comma. When I read using File.Readline()
I get it to a string[]
. I need to conver
I think this is what you are after:
static void Main(string[] args)
{
var sr = new StreamReader(@"d:\test.txt");
long[] data = ExtractData(sr).ToArray();
}
private static IEnumerable ExtractData(StreamReader sr)
{
string line;
while ((line = sr.ReadLine()) != null)
{
var items = line.Split(',');
foreach (var item in items)
{
yield return Convert.ToInt64(item);
}
}
}
With my test file (d:\test.txt) holding:
1,2,3,4,5
1,2,3,4
I get the array containing:
1,2,3,4,5,1,2,3,4
As Monroe pointed out, I missed the fact you wanted an array of arrays. Here's another version that gives such a jagged array. Still keeping yield in though ;)
static void Main(string[] args)
{
var sr = new StreamReader(@"d:\test.txt");
var data = ExtractData(sr).ToArray();
}
private static IEnumerable ExtractData(StreamReader sr)
{
string line;
while ((line = sr.ReadLine()) != null)
{
yield return line.Split(',').Select(i => Convert.ToInt64(i)).ToArray();
}
}