当我从另一个来源查询上下文时,我希望更新列表中的值
我可以使用2种不同样式的查询来查找匹配项
var r = from aa in context.Persons.GetItems()
join bb in findPersonViewModel.findPersonResultsViewModel on aa.PersonId equals bb.PersonID
select aa;
OR
var results = context.Persons.GetItems().Where(ax => findPersonViewModel.findPersonResultsViewModel.Any(b => ax.PersonId == b.PersonID));
为简单起见,我缩短了模型
public class FindPersonResultsViewModel
{
public int PersonID { get; set; }
public bool ExistInContactManager { get; set; }
public bool ActionType { get; set; }
}
public class PersonViewModel
{
public int PersonID { get; set; }
}
目标:如果PersonID匹配,则更新FindPersonResultsViewModel以将ExistinContactManager
和ActionType
都设为True
以下是视觉数据的示例
var findPersonResultsViewModel = new List<FindPersonResultsViewModel>()
{ new FindPersonResultsViewModel { PersonID = 2, ActionType = false, ExistInContactManager = false },
new FindPersonResultsViewModel { PersonID = 3, ActionType = false, ExistInContactManager = false },
new FindPersonResultsViewModel { PersonID = 4, ActionType = false, ExistInContactManager = false },
new FindPersonResultsViewModel { PersonID = 5, ActionType = false, ExistInContactManager = false },
new FindPersonResultsViewModel { PersonID = 6, ActionType = false, ExistInContactManager = false },
};
var personModel = new List<PersonViewModel>()
{ new PersonViewModel { PersonID = 2 },
new PersonViewModel { PersonID = 6 },
new PersonViewModel { PersonID = 8 },
new PersonViewModel { PersonID = 9 },
new PersonViewModel { PersonID = 12 },
new PersonViewModel { PersonID = 22 },
new PersonViewModel { PersonID = 32 },
new PersonViewModel { PersonID = 42 },
};
答案 0 :(得分:1)
如果我了解您的要求,则可以使用Contains
和foreach
var ids = personModel.Select(x => x.PersonID);
var results = findPersonResultsViewModel.Where(x => ids.Contains(x.PersonID));
foreach (var item in results)
{
item.ActionType = true;
item.ExistInContactManager = true
}
db.SaveChanges();
或者您可以仅使用Join
来保存自己的往返行程,并使用foreach
var results =
from pr in findPersonResultsViewModel
join p in personModel on pr.PersonID equals p.PersonID
select pr;
foreach (var item in results)
{
item.ActionType = true;
item.ExistInContactManager = true;
}
db.SaveChanges();
输出
PersonID : 2, ActionType :True, ExistInContactManager :True
PersonID : 3, ActionType :False, ExistInContactManager :False
PersonID : 4, ActionType :False, ExistInContactManager :False
PersonID : 5, ActionType :False, ExistInContactManager :False
PersonID : 6, ActionType :True, ExistInContactManager :True