Add SequenceEqualityComparer which implements Equals and GetHashCode in a manner compatible with Java's List interface

This commit is contained in:
Sam Harwell 2013-02-23 23:13:40 -06:00
parent a988b668d3
commit f8cce16966
2 changed files with 53 additions and 0 deletions

View File

@ -153,6 +153,7 @@
<Compile Include="Sharpen\DictionaryExtensions.cs" />
<Compile Include="Sharpen\ListExtensions.cs" />
<Compile Include="Sharpen\Runtime.cs" />
<Compile Include="Sharpen\SequenceEqualityComparer`1.cs" />
<Compile Include="TokenStreamRewriter.cs" />
<Compile Include="TokenTypes.cs" />
<Compile Include="Tree\AbstractParseTreeVisitor`1.cs" />

View File

@ -0,0 +1,52 @@
namespace Sharpen
{
using System.Collections.Generic;
using System.Linq;
public class SequenceEqualityComparer<T> : EqualityComparer<IEnumerable<T>>
{
private static readonly SequenceEqualityComparer<T> _default = new SequenceEqualityComparer<T>();
private readonly IEqualityComparer<T> _elementEqualityComparer = EqualityComparer<T>.Default;
public SequenceEqualityComparer()
: this(null)
{
}
public SequenceEqualityComparer(IEqualityComparer<T> elementComparer)
{
_elementEqualityComparer = elementComparer ?? EqualityComparer<T>.Default;
}
public new static SequenceEqualityComparer<T> Default
{
get
{
return _default;
}
}
public override bool Equals(IEnumerable<T> x, IEnumerable<T> y)
{
if (x == y)
return true;
if (x == null || y == null)
return false;
return x.SequenceEqual(y, _elementEqualityComparer);
}
public override int GetHashCode(IEnumerable<T> obj)
{
if (obj == null)
return 0;
int hashCode = 1;
foreach (T element in obj)
hashCode = 31 * hashCode + _elementEqualityComparer.GetHashCode(element);
return hashCode;
}
}
}