为什么不能更改System.Linq.Enumerable.WhereSelectListIterator集合中的对象

Bar*_*tta -2 c# linq

我使用Linq选择一些数据,返回的类型为WhereSelectListIterator。我发现无法修改WhereSelectListIterator中的对象,例如,将其设置为null或更新该值的任何属性。是设计使然吗?如何做到这一点?

using System;
using System.Collections.Generic;
using System.Linq;

namespace linqtest
{
    class Program
    {
        static void Main(string[] args)
        {

            var project = new Project()
            {
                Sections = new List<Section>()
                {
                    new Section()
                    {
                        OutDated = new char[2]{'a','d'}

                    },
                    new Section()
                    {
                        OutDated = new char[2]{'a','d'}

                    },
                    new Section()
                    {
                        OutDated = new char[2]{'a','d'}

                    }
                }
            };


            var dates = project.Sections.Select(t=>(new MyString(t.OutDated)));
            Console.Write(dates.ElementAt(0).Description);
            dates.ElementAt(0).Description = "123";
            Console.Write(dates.ElementAt(0).Description);
            Console.Read();

        }
    }


    class MyString
    {
        public MyString(char[] abc)
        {
                Description = new string(abc).Substring(1);
        }
        public string Description { set; get; }
    }
    class Project
    {
        public IEnumerable<Section> Sections;
    }
    internal class Section
    {
        public char[] OutDated;

    }
}
Run Code Online (Sandbox Code Playgroud)

toa*_*akz 5

LINQ的行为就像yield在集合上使用运算符。如果您修改集合,它将使迭代器无效。

要解决此问题,请考虑转换为具体的类,而不是IEnumerable<T>通过调用ToArray()ToList()在上进行使用IEnumerable<T>