Click here to Skip to main content
Click here to Skip to main content

Diff two lists

, 19 Dec 2010
Rate this:
Please Sign up or sign in to vote.
Drop-in Function to get the steps to convert one list to another
Often, I find myself forced to convert one whole list of items into another. For example, in a web application, I load a list of preferences from the DB, then display them to the user, who changes them and saves.
 
Then I have to figure out exactly what operation to perform to change the old list into the new one (Deleting the old and adding the new is not always the best option)
 
I found myself doing this so much I wrote a drop-in Function for it.
 
public static void GetListChanges<T>(IEnumerable<T> originalList, IEnumerable<T> newList, out List<T> itemsToRemove, out List<T> itemsToAdd)
{
    itemsToAdd = new List<T>();
    itemsToRemove = new List<T>(originalList);
    foreach (var item in newList)
    {
        if (originalList.Contains(item))
        {
            itemsToRemove.Remove(item);
        }
        else
        {
            itemsToAdd.Add(item);
        }
    }
}
 
Hope you find it as useful as I did.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

qlipoth
Software Developer (Senior) InGage Networks
United States United States
James is currently a Software developer after a detour from that profession into IT because he 'didn't want to sit in a cubicle and wanted to deal with people.' He has since learned that people are stupid, and enjoys his cubicle greatly.

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 19 Dec 2010
Article Copyright 2010 by qlipoth
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid