开发者

Why can't I edit elements of IEnumerable?

I do something like this and the value in the collection doesn't change

                [Test]
                public void EnumerableTest()
                {
                    var source = GetFoos();

                    source.First().One = "hello";

                    开发者_如何学PythonAssert.AreEqual(source.First().One, "hello");
    //it fails

                }

//I actually return this from a repository
                public IEnumerable<Foo> GetFoos()
                {
                    yield return new Foo() {One = "1", Two = "2", Three = true};
                    yield return new Foo() {One = "1", Two = "2", Three = true};
                    yield return new Foo() {One = "1", Two = "2", Three = true};
                }


That is because you create new instances each time you enumerate over GetFoos.


If you change the var source = GetFoos(); into var source = GetFoos().ToList();, the list is read immediately (and in full). Then you should be able to change the values.

Don't forget to store the changed values or else they revert the next time you read them.


It is because of your use of yield return.

You could write instead:

public IEnumerable<Foo> GetFoos()
{
    return new List<Foo>
    {
        new Foo { One = "1", Two = "2", Three = true },
        new Foo { One = "1", Two = "2", Three = true },
        new Foo { One = "1", Two = "2", Three = true },
    };
}


When you call First() a new Enumerator is created. So GetFoos() is called again and return a new object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜