Reputation: 392
I've made some code to read a file line by line using some sort of a linq way. Now I need some suggestions on how to insert each line separated by comma in the database object. I've made this on another code but it was using a while loop which is this case seems to be kind of hard for a beginner in linq. fileReader is the name of the table that works like declaring an obj for a class. DataClasses1DataContext is the class for the connection created by linq. as for now I can insert values 0,1 and 2 into the sql table but no more than that. Any help or suggestions will be highly appreciated. :) Thank you!
DataClasses1DataContext db;
private void Readbtn_Click(object sender, EventArgs e)
{
List<string> List = new List<string>();
FileReader fr = new FileReader();
var read = File.ReadAllLines(@"C:\Files\Archivo.txt").SelectMany(line => line.Split(',')).ToArray();
foreach (var word in read )
{
List.Add(word);
listBox1.Items.Add(word);
}
fr.Matricula = List[0];
fr.Nombre = List[1];
fr.Sueldo = decimal.Parse(List[2]);
db.FileReaders.InsertOnSubmit(fr);
db.SubmitChanges();
}
private void Show_Click(object sender, EventArgs e)
{
db = new DataClasses1DataContext();
dataGridView1.DataSource = db.FileReaders.ToList();
}
private void Form1_Load(object sender, EventArgs e)
{
db = new DataClasses1DataContext();
}
Upvotes: 0
Views: 800
Reputation: 3036
Hope i'm getting you right. Looks like every line in your file contains 3 values for Matricula, Nombre and Sueldo. If so, then you try to go another way:
var readers = new List<FileReader>();
System.IO.File.ReadAllLines(@"C:\Files\Archivo.txt").ToList()
.ForEach(l => {
string[] splitted = l.Split(',');
readers.Add(new FileReader(){
Matricula = splitted[0],
Nombre = splitted[1],
Sueldo = decimal.Parse(splitted[2])
});
});
Thus you have array of FileReader values. Then:
List.AddRange(readers.Select(r => r.Matricula));
listBox1.Items.AddRange(readers.Select(r => r.Matricula));
db.FileReaders.InsertAllOnSubmit(readers);
db.SubmitChanges();
Upvotes: 1