Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Hi,
How can I loop through a file containg values like the ones below, and stored them in a Tuple ?
1.1, 0.1836856, 5.6
3.3, -5.5, 43.44
-0.38162, 6.636666E-08, 3.1
1.01516E-07, 0.3695395, 1.5


thank you
C#
var reader = new StreamReader(File.OpenRead(@"C:\MyFile.txt"));

while (!reader.EndOfStream)
{
    var line = reader.ReadLine();
    var values = line.Split(',');
    
    var val1 = decimal.Parse(values[0], System.Globalization.NumberStyles.Float);
    var val2 = decimal.Parse(values[1], System.Globalization.NumberStyles.Float);
    var val3 = values[2];
    
    Tuple myTuple = Tuple.Create(val1,val2, val3);
}
Posted
Updated 18-Oct-15 0:18am
v3
Comments
[no name] 17-Oct-15 12:20pm    
Splite a line with "," as separatore should do it...
PIEBALDconsult 17-Oct-15 12:21pm    
Why didn't you simply add that to your existing question?
http://www.codeproject.com/Lounge.aspx?fid=1159&select=5143830#xx5143830xx
Kenneth Haugland 17-Oct-15 13:27pm    
You can use this:
https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser(v=vs.110).aspx
walidm38 17-Oct-15 14:50pm    
If my txt file contained simlar rows to these:
1.1, 0.1836856, 5.6
3.3, -5.5, 43.44
-0.38162, 6.636666E-08, 3.1
1.01516E-07, 0.3695395, 1.5

How can read the file into a Tuple ?
Thank you

Hide Copy Code
var reader = new StreamReader(File.OpenRead(@"C:\MyFile.txt"));

while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');

var val1 = decimal.Parse(values[0], System.Globalization.NumberStyles.Float);
var val2 = decimal.Parse(values[1], System.Globalization.NumberStyles.Float);
var val3 = values[2];

Tuple<decimal,> myTuple = Tuple.Create<decimal,decimal,string>(val1,val2, val3);

}
Tomas Takac 18-Oct-15 2:47am    
You shouldn't post code in comments, update your question instead.

1 solution

Check this:

C#
string sFile  = @"D:\MyFile.txt";

string[] lines = File.ReadAllLines(sFile);
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");

var result = lines.Select
    (
        a=> Tuple.Create(
            double.Parse(a.Split(new string[]{","}, StringSplitOptions.RemoveEmptyEntries)[0], culture),
            double.Parse(a.Split(new string[]{","}, StringSplitOptions.RemoveEmptyEntries)[1], culture)
            double.Parse(a.Split(new string[]{","}, StringSplitOptions.RemoveEmptyEntries)[2], culture)
        )
    )
    .ToList();


Returns List<Tuple<double,double,double>>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900