开发者

C# update object within foreach loop

I would like to say this was working and now it is not. I don't know what would have changed.

        var inquiry = repo.GetByInstanceId(2);

        foreach (var s in inquiry.Prop)
        {
            s.Prop = "Test 1 2 3...";
        }

        Assert.AreEqual(true, inquiry.S.Single().IsDirty, "S Should Be Dirty");

What is happening is before the Property object would get updated and everything would be grand. Now the Property is being updated within the foreach loop but after the foreach loop it's like I didn't do anything.

--EDIT-- Okay, I thinks IsDirty is throwing everyone off. I wanted to put the exact code, minus a few name changes. But IsDirty is not important here.

A basic representation of what I am doing is this:

        class test { public int check { get; set; } }

        var x = new List<test>();
        x.Add(new test(){ check = 1})开发者_如何学编程;

        foreach (var y in x)
        {
            y.check = 5;
        }

the Question is "Shouldn't this work?" I think it should, if not why? I had this working and I don't know what I have changed. I could show you my objects but I would have to modify the names so much it would be pointless. IsDirty isn't the problem. The value I am changing is changed inside the loop but not changed outside the loop.


In your added explanation you create a copy in y and modify the copy.

This happens when the type of the list items is a ValueType


I think your problem might be involved with GetByInstanceId. If that is returning an IEnumerable then it is likely that your foreach is running through the values and making the change, but then your call to Single is reiterating and losing your changes. You might want to do a ToList after GetByInstanceId. Of course this is base on the assumption that inquiry.S.Single().IsDirty is a typo and should be inquiry.Single().IsDirty. Otherwise we need more info.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜