Imad
Imad

Reputation: 7490

Update multiple columns in linq using lambda expressions

I want to update record in DataTable using Linq and Lambda Expression. I can update one column as below

dtProduct.AsEnumerable().Where(i => i.Field<long>("ProductId") == Convert.ToInt64(id)).First().SetField("Qty", qty);

cant understand how to update others :(. I am ended up with writing update several times for each column.

Upvotes: 1

Views: 4578

Answers (2)

Pavan Muppalla
Pavan Muppalla

Reputation: 9

List<DataGridViewRow> rows1 = 
             dataGridView1.Rows.Cast<DataGridViewRow>()
            .ToList()
            .FindAll(x => (x.Cells["Select"].Value=1).ToString().Equals("1")?true:false);

We are trying to find something and in disguise we are setting a value to all rows.

x.Cells["Select"].Value=1

we are least bothered about what output it gives, but our aim of setting a value to each column "Select" is succeeded.

Upvotes: -1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

I ended up with writing update several times for each column.

Your code consists of two parts:

  • Locating the instance, and
  • Setting its field.

You can reuse the results of locating the instance by introducing a variable:

var inst = dtProduct.AsEnumerable().Where(i => i.Field<long>("ProductId") == Convert.ToInt64(id)).First();

Now you can call SetField on it multiple times:

inst.SetField("Qty", qty);
inst.SetField("Price", price);
inst.SetField("Weight", weight);

Upvotes: 3

Related Questions