为什么我不能在循环内的列表中替换每个对象的 属性?

Why can't I replace each object's property in a list within loop?

为什么我不能在循环内的 IEnumerble 列表中替换每个对象的 属性?

 foreach(var group in groupedClassOptions){

            var gradeNo = group.GroupName.Split(' ')[1];

            if (gradeNo != grade0_name)
            {
                var groupTotal = temp.Where(t => t.grade.ToString().Equals(gradeNo)).First().total;
                group.GroupName += " (" + groupTotal + " students)";
            }
            else
            {

                var prepGroupTotal = temp.Where(t => t.grade.ToString().Equals("0")).First().total;
                group.GroupName += " (" + prepGroupTotal + " students)";
            }
        }

在我退出此循环后,每个 group 元素的 属性 GroupName 预计会更改,但没有更改.

示例数据 - groupedClassOptions

[GroupName: Grade Prep,

选项:[Prep A(23 名学生),Prep B(21 名学生)],

GroupName: Grade 1,

选项:[1 A(23 名学生),1 B(21 名学生)],

GroupName: Grade 2,

选项:[2 A(23 名学生),2 B(21 名学生)],

]

这只是为了让您明白,请忽略任何语法错误。 现在我想用 GroupName: Grade 1 (x students)

替换 GroupName: Grade 1

groupedClassOptions 的实现

var groupedClassOptions = dataClass.GroupBy(x => x.grade).Select(x => new OptionGroupVM()
        {
            GroupName = "Grade " + (x.Key == 0 ? grade0_name : x.Key.ToString()) /*+ " (" + (groupTotal.Where(t => t.grade.ToString().Equals(x.Key)).First().total) + " students)"*/,
            Options = x.Select(y => new OptionVM()
            {
                Value = y.classID.ToString(),
                Text = x.Key == 0 ? grade0_name + y.classname.Substring(1) + " (" + y.total + " students)" : y.classname + " (" + y.total + " students)"
            })
        });

您需要使用 ToList() 方法将 groupedClassOptions 转换为列表,这使得 list 中的对象可更新。

var groupedClassOptions = dataClass.GroupBy(x => x.grade).Select(x => new OptionGroupVM()
        {
            GroupName = "Grade " + (x.Key == 0 ? grade0_name : x.Key.ToString()) /*+ " (" + (groupTotal.Where(t => t.grade.ToString().Equals(x.Key)).First().total) + " students)"*/,
            Options = x.Select(y => new OptionVM()
            {
                Value = y.classID.ToString(),
                Text = x.Key == 0 ? grade0_name + y.classname.Substring(1) + " (" + y.total + " students)" : y.classname + " (" + y.total + " students)"
            })
        }).ToList();

现在,更新上面列表中的对象。

不更新 IEnumerable 内部对象的原因发布在 following answer:

IEnumerables do not guarantee that updated values will persist across enumerations. For instance, a List will return the same set of objects on every iteration, so if you update a property, it will be saved across iterations. However, many other implementations of IEnumerables return a new set of objects each time, so any changes made will not persist.