我希望在从另一个来源查询上下文时更新列表中的值
我可以找到 2 种不同风格的查询的匹配项
var r = from aa in context.Persons.GetItems()
join bb in findPersonViewModel.findPersonResultsViewModel on aa.PersonId equals bb.PersonID
select aa;
或
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 },
};
最佳答案
如果我明白你在问什么......你可以只使用 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
关于c# - 使用 Linq 从另一个具有匹配值的列表更新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56571911/