所以我有一个函数可以从Web服务获取学生列表,还可以查询localdb中的所有学生。数据放在两个不同的列表中。所以我想查看localdb列表中是否已经存在新学生。如果是,请更新它,如果没有,则添加它。我无法让它工作。我试图使用LINQ执行此操作,但我似乎无法使其正常工作。我的LINQ技能充其量只是业余。
public async Task GetStudents()
{
String controllerName = "Students";
List<Students> newStudentData = await RunGetAsync<Students>(controllerName);
// get all the service types that already exists in the localStudent Db
List<Students> currentStudentData = db.Studentss.ToList();
foreach (Students existingStudents in currentStudentData)
{
foreach (Students newStudents in newStudentData)
{
IEnumerable<Students> selectStudents = from student in newStudentData // check if Students exist in the database
where student.Id == existingStudents.Id
select student;
if (selectStudents == null) // didn't find it, then add it
{
db.Students.Add(newStudents);
}
if (selectStudents != null) // found it , then update the informations
{
Students updatedStudents = new Students();
foreach (var field in selectStudents)
{
updatedStudents.FName = field.FName;
updatedStudents.LName = field.LName;
updatedStudents.ZipCode = field.ZipCode;
updatedStudents.AccessCode = field.AccessCode;
}
db.Entry(updatedStudents).State = System.Data.Entity.EntityState.Modified;
}
}
}
db.SaveChanges();
}
非常感谢你的帮助。
答案 0 :(得分:4)
您的循环次数超出了您的需求:
foreach (Students newStudents in newStudentData)
{
var student = currentStudentData.FirstOrDefault(s => s.Id == newStudents.Id);
if(student == null)
{
//add
}
else
{
//update
}
}
使用FirstOrDefault
,您可以查看它是否存在并同时获取对它的引用,如果存在的话。
答案 1 :(得分:0)
您可以使用Intersect和Except,如下所示:
//Find students that already exist to update
var updateStudents = currentStudentData.Intersect(newStudentData);
//Find new students to add
var addStudents = newStudentData.Except(currentStudentData);