2

I have a DataTable and an array of objects that I loop through.

For each row in a data table, I search through my collection of objects with Linq, and if found, that object needs to be updated. But how do I refresh my collection without reloading it from the database?

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.
             }

How else can I search and update a single item in the array?

1
  • 2
    As an aside, I think you mean if (found == null) Commented Aug 2, 2013 at 12:23

1 Answer 1

8

You don't need to update your collection - assuming Car is a class, you've already updated the object that the array refers to by setting found.updated to true.

Don't forget that the array only contains references - so the found reference is the same reference which is in the array; updating the object via either variable will result in the change being visible via the other one.

Sign up to request clarification or add additional context in comments.

2 Comments

References you say. Interesting. Will test it. Thanks.
@user1208908: Yes. This is part of the core of C# - it's really important that you understand how objects and references work in C#. See pobox.com/~skeet/csharp/references.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.