在列表中搜索匹配的对象并指定值
本文关键字:对象 列表 搜索 | 更新日期: 2023-09-27 18:04:45
我的类
class student
{
public string studentid { get; set; }
public string groupid { get; set; }//Group id
}
我的列表
List<student> pupils = new List<student>();
在这里我选择没有团体id 的学生
var studentsWithNoGroupId = from student in pupils
where student.groupid =="00"
select student;
我想通过一个for循环,它运行的次数等于studentsWithNoGroupId.Count,并用我的一些值分配组ID。(仅仅展示如何分配每个对象就足够了(。如何做到这一点?
或者我必须为此更改我的linq吗?请有人帮帮我。
pupils.Where(p => p.groupid == "00")
.ToList()
.ForEach(
p => {
p.groupid = "whatever";
});
编辑(在Hatsjoem提示之后,更简单(:
pupils.FindAll(p => p.groupid == "00")
.ForEach(p => {
p.groupid = "whatever";
});
你的意思是这样的吗?
var studentsWithNoGroupId =
from student in pupils
where student.groupid =="00"
select student;
foreach(var student in studentsWithNoGroupId)
{
student.groupid = "x";
}
您的线路:
var studentsWithNoGroupId = from student in pupils
where student.groupid =="00"
select student;
创建一个Linq查询。此查询不会立即执行。要执行它,请尝试以下操作:
var studentsWithNoGroupIdQuery = from student in pupils
where student.groupid =="00"
select student;
var studentsWithNoGroupId = studentsWithNoGroupIdQuery.ToList();
foreach (var student in studentsWithNoGroupId)
{
student.groupid = // Your logic here.
}
// Save pupils back to the database here.
ToList((使查询执行并将结果存储在List<student>
中。在迭代之前执行查询非常重要,因为您正在更改筛选查询的同一变量groupid
。
我不知道这是否是你想要的,但我会尝试一下:
var yourPupils = pupils.Where(p => p.groupid == "00")
.Select(s => new student() {
studentid = s.studentid,
groupid = "yourCustomAssignedId"
}).ToList();
对于循环版本:
var numberOfPupils = pupils.Count();
for (int i = 0; i < numberOfPupils; i++)
{
if (pupils[i].groupid == "00")
{
pupils[i].groupid = "yourCustomAssignedId";
}
}