user1092280
user1092280

Reputation:

modify items in a Generic List

i cannot modify generic List with :

var x = (PaypalResponse)Session["PaypalResponse"]; // x.Response is my List

x.Response.ToList().Where(i => i.Id== 1).ForEach(s => s.Selected = true);

where am I doing wrong? Thanks.

Upvotes: 1

Views: 2339

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149058

You could do this:

x.Response.Where(i => i.Id == 1).ToList().ForEach(s => s.Selected = true);

However, it's a bit of a waste of resources to construct a new list just for this one line of code. I'd recommend this instead:

foreach(var s in x.Response.Where(i => i.Id == 1))
{
    s.Selected = true;
}

If you only want to update at most one item, you can do this instead:

var s = x.Response.FirstOrDefault(i => i.Id == 1);
if (s != null)
{
    s.Selected = true;
}

And of course, if you know there will be one item to update, it's even easier:

x.Response.First(i => i.Id == 1).Selected = true;

Upvotes: 1

Related Questions