Actually it depends on the collection. In some cases, LINQ methods can return cloned objects instead of references to originals. Take a look at this test:
[Test]
public void Test_weird_linq()
{
var names = new[]{ "Fred", "Roman" };
var list = names.Select(x => new MyClass() { Name = x });
list.First().Name = "Craig";
Assert.AreEqual("Craig", list.First().Name);
}
public class MyClass
{
public string Name { get; set; }
}
This test will fail, even though many people believe that the same object will be returned by list.First()
. It will work if you use another collection "modified with ToList()
".
var list = names.Select(x => new MyClass() { Name = x }).ToList();
I don't know for sure why it works this way, but it's something to have in mind when you write your code :)
This question can help you understand how LINQ works internally.