我的班级
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吗? 请有人帮助我。
答案 0 :(得分:1)
你的意思是这样的吗?
var studentsWithNoGroupId =
from student in pupils
where student.groupid =="00"
select student;
foreach(var student in studentsWithNoGroupId)
{
student.groupid = "x";
}
答案 1 :(得分:1)
pupils.Where(p => p.groupid == "00")
.ToList()
.ForEach(
p => {
p.groupid = "whatever";
});
编辑(在Hatsjoem暗示之后,更简单):
pupils.FindAll(p => p.groupid == "00")
.ForEach(p => {
p.groupid = "whatever";
});
答案 2 :(得分:0)
你的专栏:
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
。
答案 3 :(得分:0)
我不知道这是不是你要找的,但我会试一试:
var yourPupils = pupils.Where(p => p.groupid == "00")
.Select(s => new student() {
studentid = s.studentid,
groupid = "yourCustomAssignedId"
}).ToList();
For-loop版本:
var numberOfPupils = pupils.Count();
for (int i = 0; i < numberOfPupils; i++)
{
if (pupils[i].groupid == "00")
{
pupils[i].groupid = "yourCustomAssignedId";
}
}