Update DataTable Values Using LINQ In C# And VB.NET
Hello,
Here's how to update DataTable value(s) using Method or Query syntax in LINQ.
C# Code
VB.NET
Output
Here's how to update DataTable value(s) using Method or Query syntax in LINQ.
C# Code
private void Form1_Load(object sender, EventArgs e) { DataTable dt = new DataTable("tblEntTable"); dt.Columns.Add("ID", typeof(string)); dt.Columns.Add("Amount", typeof(decimal)); dt.Rows.Add(new object[] {"1", 100.51}); dt.Rows.Add(new object[] {"2", 200.52}); dt.Rows.Add(new object[] {"3", 500.24}); dt.Rows.Add(new object[] {"4", 400.31}); dt.Rows.Add(new object[] {"5", 600.88}); dt.Rows.Add(new object[] {"6", 700.11}); //QuerySyntax(dt); MethodSyntax(dt); } private void QuerySyntax(DataTable dt) { var result = from row in dt.AsEnumerable() select new { ID = row.Field<string>("ID"), Amount = 900.23 }; DataGridView1.DataSource = result.ToList(); } private void MethodSyntax(DataTable dt) { Array.ForEach(dt.AsEnumerable().ToArray(), (row)=>{ row["Amount"] = 800; }); DataGridView1.DataSource = dt; }
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim dt As New DataTable("tblEntTable") dt.Columns.Add("ID", GetType(String)) dt.Columns.Add("Amount", GetType(Decimal)) dt.Rows.Add(New Object() {"1", 100.51}) dt.Rows.Add(New Object() {"2", 200.52}) dt.Rows.Add(New Object() {"3", 500.24}) dt.Rows.Add(New Object() {"4", 400.31}) dt.Rows.Add(New Object() {"5", 600.88}) dt.Rows.Add(New Object() {"6", 700.11}) MethodSyntax(dt) 'QuerySyntax(dt) End Sub Sub MethodSyntax(ByVal dt As DataTable) Array.ForEach(dt.AsEnumerable().ToArray(), Sub(row) row("Amount") = 900.23) DataGridView1.DataSource = dt End Sub Sub QuerySyntax(ByVal dt As DataTable) Dim result = From row In dt.AsEnumerable() Select New With { _ .ID = row.Field(Of String)("ID"), _ .Amount = 800 } DataGridView1.DataSource = result.ToList() End Sub
Comments
Post a Comment