Last active
October 11, 2017 19:13
-
-
Save glenndierckx/53a22f54ab76ccfb79ad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace CollectionHelpers | |
{ | |
public static class MergeHelper | |
{ | |
public static void Merge<TCurrent, TToBe, TId>( | |
this IEnumerable<TCurrent> current, | |
IEnumerable<TToBe> toBe, | |
Func<TCurrent, TId> currentIdSelector, | |
Func<TToBe, TId> toBeIdSelector, | |
Action<TToBe> onAdd = null, | |
Action<TCurrent, TToBe> onUpdate = null, | |
Action<TCurrent> onRemove = null) | |
{ | |
var currentList = current.ToList(); | |
var toBeList = toBe.ToList(); | |
var leftOuterJoin = currentList.GroupJoin(toBeList, currentIdSelector, toBeIdSelector, | |
(currentEntity, toBeEntity) => new | |
{ | |
currentEntity, | |
toBeEntity = toBeEntity.DefaultIfEmpty().SingleOrDefault() | |
}); | |
var rightOuterJoin = toBeList.GroupJoin(currentList, toBeIdSelector, currentIdSelector, | |
(toBeEntity, currentEntity) => new | |
{ | |
currentEntity = currentEntity.DefaultIfEmpty().SingleOrDefault(), | |
toBeEntity | |
}); | |
var fullOuterJoin = leftOuterJoin.Union(rightOuterJoin).ToArray(); | |
foreach (var entity in fullOuterJoin) | |
if (Equals(entity.toBeEntity, null)) | |
onRemove?.Invoke(entity.currentEntity); | |
else if (Equals(entity.currentEntity, null)) | |
onAdd?.Invoke(entity.toBeEntity); | |
else | |
onUpdate?.Invoke(entity.currentEntity, entity.toBeEntity); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment