Getting Added And Deleted Items In A List Using LINQ

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.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)
                                           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)
                                           select actualItem;

Hope this snippet helps you somewhere.

Author : image Jebarson Jebamony.   image  @jebarson007


Jebarson is a consultant at Microsoft. In his overall experience of 7+ years, his expertise ranges from VB6, COM / DCOM, .net,, WPF, WCF, SL, SQL. He has a greater love for OOA / OOD and SOA. His current focus is on Azure, Windows Phone 7, Crm and much more. He is also a frequent speaker of different community events. He blogs at . You can follow him at @Jebarson007 . Jebarson having good set of tutorials written on Windows Azure, you can found them . He is a contributor of this site and shared many tips and tricks.

One Comment to “Getting Added And Deleted Items In A List Using LINQ”

Comments are closed.