使用 LINQ ForEach 设置列表属性值
本文关键字:属性 列表 设置 LINQ ForEach 使用 | 更新日期: 2023-09-27 18:36:01
>我正在使用下面的linq查询来设置SecKey的值,但我仍然在列表中看到旧值 studentData,
在 id 下方是我正在使用的示例,该示例不起作用/未设置值,
studentData.Where(w => w.ActiveDate.Date.Equals(otherObject.ActiveDate.Date) && w.EndDate.Date.Equals(otherObject.EndDate.Date)).ToList().ForEach(s => s.SecKey = secKey);
在这里我编造了一些数据,
public struct Student
{
public string BadgeNum;
public DateTime ActiveDate;
public DateTime EndDate;
public decimal Amount;
public decimal? SecKey;
}
List<Student> students = new List<Student>();
students.Add(new Student() {
BadgeNum = "1"
,
ActiveDate = new DateTime(2014,4,4)
,
EndDate = new DateTime(2014, 5, 6)
,
Amount = 10
,
SecKey = 1
});
students.Add(new Student()
{
BadgeNum = "1"
,
ActiveDate = new DateTime(2014, 5, 6)
,
EndDate = new DateTime(2014, 5, 9)
,
Amount = 10
,
SecKey = 1
});
students.Add(new Student()
{
BadgeNum = "1"
,
ActiveDate = new DateTime(2014, 5, 9)
,
EndDate = new DateTime(2014, 6, 6)
,
Amount = 10
,
SecKey = 1
});
foreach (var b in students)
{
if (b.ActiveDate.Date.Equals(new DateTime(2014, 5, 9)) && b.EndDate.Date.Equals(new DateTime(2014, 6, 6)))
{
b.SecKey = 1;
}
}
您有一个可变值类型,因此当您迭代集合时,您将复制所有项目并更改该副本,使列表中的值保持不变。
如果要继续在此处使用值类型,则需要将突变值分配回列表中的相应位置。
实际上,您根本不应该在这里使用值类型,特别是应该避免可变值类型,部分原因是这种情况,您最终会在不知不觉中更改您打算更改的值的副本。 更可取的解决方案是简单地将类型更改为class
。
如果您想在不创建新列表的情况下实现目标,请尝试以下操作:
foreach (var student in studentData.Where(w => w.ActiveDate.Date.Equals(otherObject.ActiveDate.Date) && w.EndDate.Date.Equals(otherObject.EndDate.Date)))
{
student.SecKey = secKey;
}
编辑:这是在假设学生是class
而不是struct
的情况下创建的。
一旦你在查询中执行ToList,它将返回新列表。
var newlist = studentData.Where(w => w.ActiveDate.Date.Equals(otherObject.ActiveDate.Date) && w.EndDate.Date.Equals(otherObject.EndDate.Date)).ToList();
newlist.ForEach(s => s.SecKey = secKey);