Skip to content

Instantly share code, notes, and snippets.

@tomasaschan
Created November 20, 2017 08:37
Show Gist options
  • Select an option

  • Save tomasaschan/e00dbae3deabcdf95a7ab07f9c308db7 to your computer and use it in GitHub Desktop.

Select an option

Save tomasaschan/e00dbae3deabcdf95a7ab07f9c308db7 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using AutoMapper;
using Newtonsoft.Json;
namespace SetsWithEqualityComparers
{
internal class Program
{
private static void Main()
{
var mapper = new MapperConfiguration(cfg =>
{
cfg.CreateMap<StuffSource, StuffDest>()
.ForMember(dest => dest.Things,
opt => opt.UseValue(new HashSet<IResource>(new ResourceEqualityComparer<IResource>())))
.AfterMap((src, dest) =>
{
dest.Things.UnionWith(src.Foos);
dest.Things.UnionWith(src.Bars);
});
}).CreateMapper();
var foos = new[]
{
new Foo {Id = "1"},
new Foo {Id = "2"},
new Foo {Id = "1"}
};
var bars = new[]
{
new Bar {Id = "1"},
new Bar {Id = "1"}
};
var stuff = new StuffSource
{
Foos = foos,
Bars = bars
};
var things = mapper.Map<StuffDest>(stuff);
Console.WriteLine(JsonConvert.SerializeObject(things.Things));
var set = new HashSet<IResource>(new ResourceEqualityComparer<IResource>());
set.UnionWith(foos);
set.UnionWith(bars);
Console.WriteLine(JsonConvert.SerializeObject(set));
Console.WriteLine(things.Things.SetEquals(set));
}
}
public class StuffSource
{
public IEnumerable<Foo> Foos { get; set; }
public IEnumerable<Bar> Bars { get; set; }
}
public class StuffDest
{
public ISet<IResource> Things { get; set; }
}
public class Foo : IResource
{
public string Type { get; } = "Foo";
public string Id { get; set; }
}
public class Bar : IResource
{
public string Type { get; } = "Bar";
public string Id { get; set; }
}
public interface IResource
{
string Type { get; }
string Id { get; }
}
public class ResourceEqualityComparer<T> : IEqualityComparer<T> where T : IResource
{
public bool Equals(T x, T y)
=> x != null && y != null
&& EqualityComparer<string>.Default.Equals(x.Id, y.Id)
&& EqualityComparer<string>.Default.Equals(x.Type, y.Type)
|| x == null && y == null;
public int GetHashCode(T obj)
{
if (obj == null) throw new ArgumentNullException(nameof(obj));
return EqualityComparer<string>.Default.GetHashCode(obj.Id) + 191 * EqualityComparer<string>.Default.GetHashCode(obj.Type);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment