c# - 更新数组中的特定对象

标签 c# arrays linq

我有一个 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/

相关文章:

c# - LINQ In Clause With Group By 和每个组中的 TOP N 记录

c# - "No imaging component suitable to complete this operation was found."

javascript - highcharts 不读取数据,只处理假数据

java - 如何在android中为固定的IMEI生成固定的字节数组

c - 关于将 char[] 传递给 isdigit()

c# - LINQ to SQL 从多对多表中选择完全匹配的记录

与原始查询相比,C# LINQ 查询创建低效的 SQL

c# - LINQ to SQL 特性

c# - 需要在网页上的两点之间画一条线

C# 每个 Grpc 一元调用重用或创建新客户端