Woody
Woody

Reputation: 1797

Find an object within a list and replace its value

I have the following list and class:

List<MyClass> MyList

public class MyClass
{
    public int id { get; set; }
    public bool checked { get; set; }
}

I also have the two variables:

int idToFind = 1234;
bool newcheckedvalue = true;

What I need to do is search the list and find the MyClass object where the id equals that value of idToFind. Once I have the object in the list, I then want to change the value of the checked property in the class to that of the newcheckedvalue value.

LINQ seems to be the solution to this problem, I just can't get the expression right. Can I do this in a single LINQ expression?

Upvotes: 1

Views: 6485

Answers (2)

Habib
Habib

Reputation: 223422

LINQ is for querying collection, not for modification. You can find the object like:

var item = MyList.FirstOrDefault(r=> r.id == idtoFind && r.checked == newcheckedvalue);

To find the item based on the ID only you can do:

var item = MyList.FirstOrDefault(r=> r.id == idtoFind);

Later you can set/modify its property.

//Make sure to check against Null, as if item is not found FirstOrDefault will return null
item.checked = newcheckedvalue; //or any other value

Upvotes: 6

Tigran
Tigran

Reputation: 62265

Example (to be noted that MyClass type has to be a class, a reference type, in this example):

var found  = MyList.Where(ml=>ml.Id == 1234); 
foreach(var f in found)
    f.checked = newcheckedvalue;

Upvotes: 2

Related Questions