Click here to Skip to main content
15,885,200 members
Articles / Programming Languages / C#
Tip/Trick

Diff two lists

Rate me:
Please Sign up or sign in to vote.
5.00/5 (8 votes)
19 Dec 2010CPOL 18.6K   5  
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.

MIDL
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)


Written By
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 --