1

I'm using a list adding items from a class. I need to replace all items in same row using where statement. Example

 public class Foo
    {
        public string name { get; set; }
        public string SubName { get; set; }

    }

    private void button1_Click(object sender, EventArgs e)
    {
        List<Foo> mItems = new List<Foo>();
        mItems.Add(new Foo { name = "Name", SubName = "Subname" });
        mItems.Add(new Foo { name = "Name2", SubName = "Subname2" });
        mItems.Add(new Foo { name = "Name3", SubName = "Subname3" });
        if (mItems.Any(x => x.name == "Name3"))
        { 
            //where name is Name3 replace Name3 with Name4 and SubName3 with Subname4
        }
    }

I need to replace where name is Name3 the both of values. Name3 and subname3. I tried to use replace but it doesn't show it in suggested.

1 Answer 1

2

I think this is what you are looking for:

mItems.Where(x => x.name == "Name3" && x.SubName == "SubName3").ToList().ForEach(x => {
    x.name = "Name4";
    x.SubName = "SubName4";
});
Sign up to request clarification or add additional context in comments.

3 Comments

I would avoid that unnecessary .ToList()
Just do a normal foreach and you save one iteration of the collection.
@Magnus OP wanted to use Where though.

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.