Why doesn't setting a property on an enumerated object work?

I know a lot about C #, but that pushes me, and Google doesn't help.

I have an IEnumerable range of objects. I want to set the property on the first. I do this, but when I list the range of objects after modification, I do not see the changes.

Here is a good example of a problem:

    public static void GenericCollectionModifier()
    {
        // 1, 2, 3, 4... 10
        var range = Enumerable.Range(1, 10);

        // Convert range into SubItem classes
        var items = range.Select(i => new SubItem() {Name = "foo", MagicNumber = i});

        Write(items);  // Expect to output 1,2,3,4,5,6,7,8,9,10

        // Make a change
        items.First().MagicNumber = 42;

        Write(items);  // Expect to output 42,2,3,4,5,6,7,8,9,10
        // Actual output: 1,2,3,4,5,6,7,8,9,10
    }

    public static void Write(IEnumerable<SubItem> items)
    {
        Console.WriteLine(string.Join(", ", items.Select(item => item.MagicNumber.ToString()).ToArray()));
    }

    public class SubItem
    {
       public string Name;
       public int MagicNumber;
    }

What aspect of C # stops changing my "MagicNumber = 42"? Is there a way I can force my changes to stick without doing any funky conversions to List <> or array?

Thank! -Mike

+3
source share
5 answers

When you call First (), it lists the result of this bit of code:

Select(i => new SubItem() {Name = "foo", MagicNumber = i});

, Select , , ( , ). , items.First() SubItem. Write, SubItem, , .

, - :

var items = range.Select(i => new SubItem() {Name = "foo", MagicNumber = i}).ToList();
+8

, - . , - , IEnumerables .

, "ToList()" Select() ""?

0

, , , items.First() SubItem , .

I have to assume that this has something to do with IQueryable, only being able to repeat once. You can try changing this:

// Convert range into SubItem classes
var items = range.Select(i => new SubItem() {Name = "foo", MagicNumber = i});

to

// Convert range into SubItem classes
var items = range.Select(i => new SubItem() {Name = "foo", MagicNumber = i}).ToList();

And see if there are other results.

0
source

You cannot / should not change the collection through the counter. I am surprised that this is no exception.

0
source

.First () is a method, not a property. It returns a new instance of the object in the first position of your Enumerable.

0
source

All Articles