C# 更新数组中的特定对象
我有一个数据表和一个循环使用的对象数组 对于数据表中的每一行,我使用Linq搜索对象集合,如果找到,则需要更新该对象。 但是如何在不从数据库重新加载收藏的情况下刷新收藏C# 更新数组中的特定对象,c#,arrays,linq,C#,Arrays,Linq,我有一个数据表和一个循环使用的对象数组 对于数据表中的每一行,我使用Linq搜索对象集合,如果找到,则需要更新该对象。 但是如何在不从数据库重新加载收藏的情况下刷新收藏 Car[] mycars = Cars.RetrieveCars(); //This is my collection of objects //Iterate through Cars and find a match using (DataTable dt = data.ExecuteDataSet(@"SELECT *
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
引用与数组中的引用相同;通过其中一个变量更新对象将导致通过另一个变量可以看到更改。顺便说一句,我认为您的意思是if(found==null)
引用您所说的。有趣。我们将测试它。谢谢。@user1208908:是的。这是C#核心的一部分-了解对象和引用在C#中的工作方式非常重要。看见