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.
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.