我有一个 DataTable 和一个循环遍历的对象数组。
对于数据表中的每一行,我使用 Linq 搜索我的对象集合,如果找到,则需要更新该对象。 但是,如何在不从数据库重新加载的情况下刷新我的收藏?
Car[] mycars = Cars.RetrieveCars(); //This is my collection of objects
//Iterate through Cars and find a match
using (DataTable dt = data.ExecuteDataSet(@"SELECT * FROM aTable").Tables[0])
{
foreach (DataRow dr in dt.Rows) //Iterate through Data Table
{
var found = (from item in mycars
where item.colour == dr["colour"].ToString()
&& item.updated == false
select item).First();
if (found == null)
//Do something
else
{
found.updated = true;
Cars.SaveCar(found);
//HERE: Now here I would like to refresh my collection (mycars) so that the LINQ searches on updated data.
//Something like mycars[found].updated = true
//But obviously mycars can only accept int, and preferably I do not want to reload from the database for performance reasons.
}
我还能如何搜索和更新数组中的单个项目?
最佳答案
您不需要更新您的集合 - 假设 Car
是一个类,您已经通过设置 found.updated
更新了数组引用的对象为 true
。
不要忘记该数组仅包含引用 - 因此found
引用与数组中的引用相同;通过任一变量更新对象将导致更改通过另一个变量可见。
关于c# - 更新数组中的特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18016725/