65.9K
CodeProject is changing. Read more.
Home

Diff two lists

starIconstarIconstarIconstarIconstarIcon

5.00/5 (8 votes)

Nov 25, 2010

CPOL
viewsIcon

18850

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.