90's SriLankan kids know this 💭💬 :
As a So SriLankan 90's kid, this is a most loving 😍 advertisement of mine about the difference between the goose (පාත්තයා) vs. the duck (තාරාව).
The goose has some unique properties vs. the duck. Most of the properties differ from them. let's identify and compare the duck's properties list vs. the goose's using ChangeTracker class😁
Caption :
"එකෙක් තාරාවෙක් අනිකා පාත්තයෙක්. තාරවට බෑ පාත්තයා වෙන්න. පාත්තයට බෑ තාරාව වෙන්න" 😁😂😄😃
Back to topic
I created ChangeTracker class two or two three months back. But unfortunately, I forgot to write a blog regarding this. I am writing this blog post about how I use the ChangeTracker class in my project.
Some types of query operations in C#, such as Except, Distinct, Union, and Concat, can do the job (Microsoft doc guidance). But I want to build a standard interface to track changes between two lists using Linq and predicates.
UseCase
Widely I applied these scenarios in database Linq queries. I have one list that retrieves from a database table. Then this old data list should be updated top of the new list.
Considering two lists:
- I used the AddedItem list to insert into the database table
- Also, the RemovedItem list is used to delete from the database using Linq.
- The UpdateItem list helped to update my data in the table.
Thinking and Implementation
There are two collections: one database list called "oldValues" and one new list called "newValues." I receive items from time to time in the "newValues" collection. I want to know which elements were added, removed, or altered. I can compare identity id/ids in the generic Object.
Here is the proposed code snippet of the ChangeTracker<T1, T2> class.
As I said above, you must identify how the Object is unique. You can use an equals predicate, shown below.
In this example, It uses two int arrays. No big deal, We can equal elements using the Equals method or == operator.
But in this example, we use custom object arrays. We can use predicate using properties to identify equal values from identity properties.
Finally, you received newPersonItems , removedPersonItems , updatedPersonItems individual three lists, and now you can manipulate them your way.
See you again soon. ✌✌