Most the time when we work with a list object, finding a newly added items or deleted items becomes a very trivial part of the logic. Sometimes, we endup writing sophisticated logic or loops to get this done. Below code will demonstrate how this can be easily done using LINQ.
Lets assume that we have a list as below.
List actualList = new List(); actualList.Add(new MyClass() { Id = 1, FirstName = "First Name1", LastName = "Last Name1" }); actualList.Add(new MyClass() { Id = 2, FirstName = "First Name2", LastName = "Last Name2" }); actualList.Add(new MyClass() { Id = 3, FirstName = "First Name3", LastName = "Last Name3" });
Below is the list which will mimic as we have removed 2 items from the list and added 1 item.
List<MyClass> updatedList = new List<MyClass>(); updatedList.AddRange(actualList); updatedList.RemoveAt(0); updatedList.RemoveAt(1); updatedList.Add(new MyClass() { Id = 4, FirstName = "First Name4", LastName = "Last Name4" });
Below LINQ query will give you deleted items from the orginal list.
IEnumerable<MyClass> deletedItems = (IEnumerable<MyClass>)from actualItem in actualList where ! (from newItem in updatedList select newItem.Id) Contains(actualItem.Id) select actualItem;
Below LINQ query will give you added items to the orginal list.
IEnumerable<MyClass> addedItems = (IEnumerable<MyClass>)from actualItem in updatedList where ! (from newItem in actualList select newItem.Id) Contains(actualItem.Id) select actualItem;
Hope this snippet helps you somewhere.
Getting Added And Deleted Items In A List Using LINQ