Skip to content

Instantly share code, notes, and snippets.

@glenndierckx
Last active October 11, 2017 19:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glenndierckx/53a22f54ab76ccfb79ad to your computer and use it in GitHub Desktop.
Save glenndierckx/53a22f54ab76ccfb79ad to your computer and use it in GitHub Desktop.
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