1

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?

1
  • If the ids are unique across instances you could put them in a Dictionary<int, MyClass> instead then it would be as simple as MyDictionary[idToFind].checked = newcheckedvalue;. Commented May 29, 2015 at 15:33

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

3 Comments

!= newcheckedvalue, surely? And then item.checked = newcheckedvalue.
Of course as usual, you might need to handle the default (null) case. But yeah .FirstOrDefault is the way to go.
@CharlesMager, you made me thinking, I guess the OP wants to find records based on id only.
2

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.