I have this class which implements the IEquatable<T> interface
public class ArticleDescriptionDetails : IEquatable<ArticleDescriptionDetails>
{
public string Code { get; set; }
public string Value { get; set; }
public bool Hidden { get; set; }
public bool Equals(ArticleDescriptionDetails other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Code == other.Code;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((ArticleDescriptionDetails) obj);
}
public override int GetHashCode() => ((Code != null ? Code.GetHashCode() : 0) * 397) ^ Hidden.GetHashCode();
public static bool operator ==(ArticleDescriptionDetails left, ArticleDescriptionDetails right) => Equals(left, right);
public static bool operator !=(ArticleDescriptionDetails left, ArticleDescriptionDetails right) => !Equals(left, right);
}
I need this beacuse I'm tring to return an IEquatable<ArticleDescriptionDetails> in this way:
return result.OrderBy(x => x.Code).ThenBy(y => y.Hidden).Distinct();
Is there a way to do the same thing without using the IEquatable<T> interface?
You could use a DistinctBy method and do
return result.OrderBy(x => x.Code).ThenBy(y => y.Hidden).DistinctBy(z => z.Code);
But the DistinctBy method doesn't exist in linq but you can find it in the morelinq package https://www.nuget.org/packages/MoreLinq.Source.MoreEnumerable.DistinctBy/
But it's also easy to code your own version of the method :
You first need to define an IEqualityComparer
public class KeyEqualityComparer<T, K> : IEqualityComparer<T>
{
private readonly Func<T, K> selector;
public KeyEqualityComparer(Func<T, K> keySelector)
{
selector = keySelector;
}
public bool Equals(T x, T y)
{
return selector(x).Equals(selector(y));
}
public int GetHashCode(T obj)
{
return selector(obj).GetHashCode();
}
}
And the you can use this IEqualityComparer in the Distinct method :
public static IEnumerable<T> DistinctBy<T, K>(this IEnumerable<T> list, Func<T, K> keySelector)
{
var equalityComparer = new KeyEqualityComparer<T, K>(keySelector);
return list.Distinct(equalityComparer);
}
Related
I'm trying to find out how to remove that possible null reference in the IEquatable implementation below.
return other != null && _guid == other._guid; Possible null reference argument for parameter 'left' in 'bool SubscriptionToken.operator !=(SubscriptionToken left, SubscriptionToken right)'
public class SubscriptionToken : IEquatable<SubscriptionToken>
{
public static readonly SubscriptionToken Empty = new(Guid.Empty);
private readonly Guid _guid;
private SubscriptionToken(Guid guid)
{
_guid = guid;
}
private SubscriptionToken()
{
}
public Guid Value => _guid;
public bool Equals(SubscriptionToken? other)
{
return other != null && _guid == other._guid; // Possible null reference
}
public bool IsValid()
{
return _guid != Guid.Empty;
}
public static SubscriptionToken New()
{
return new SubscriptionToken(Guid.NewGuid());
}
public override bool Equals(object? other)
{
return other is SubscriptionToken token && Equals(token);
}
public override int GetHashCode()
{
return HashCode.Combine(_guid);
}
public override string ToString()
{
return _guid.ToString("N");
}
public static bool operator ==(SubscriptionToken left, SubscriptionToken right)
{
return EqualityComparer<SubscriptionToken>.Default.Equals(left, right);
}
public static bool operator !=(SubscriptionToken left, SubscriptionToken right)
{
return !(left == right);
}
}
Your equals method should probably look something like this:
public bool Equals(SubscriptionToken other)
{
if (ReferenceEquals(null, other)) return false;
return _guid.Equals(other._guid);
}
That should avoid any null reference exceptions.
i have trouble in adding duplicate element to a list
i want to add that object:
public class Allegato : BaseObject<Allegato, int>
{
public override int Id { get; set; }
public virtual string NomeFile { get; set; }
}
in BaseObject i implement equals looking only at Id Field
i cannot change this settings since those is need to my NHibernate Data Access Infrastracture
now i have other class with a list of Allegato objects
public class Corso : BaseObject<Corso, int>
{
public virtual ICollection<Allegato> Allegati { get; set; } = new List<Allegato>();
public virtual void AddAllegato(Allegato allegato)
{
this.Allegati.Add(allegato);
}
}
Now i need to add many Allegato to collection and then save it to database, ID will be empty since will be generate by DB sequence
using (myUow = myUowFactory.Create())
{
var obj = new Corso();
//populate corso
myUow.Corsi.Create(obj);
var files = SessionManagement.LeggiOggetto<SessionObject.File>(HttpContext, SessionManagement.ChiaveSessione.File);
foreach (var file in files)
obj.AddAllegato(new Allegato { NomeFile = file.Nome });
myUow.SaveAll();
}
first object is added but all other no. first element remain all others are not added
debugging it see that equals method of Allegato class is called, how can i avoid it?
thanks
EDIT
base object class
public abstract class BaseObject<TEntity, TKey> : EquatableObject<TEntity>
where TEntity : class
{
public abstract TKey Id { get; set; }
public override int GetHashCode()
{
return Id.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
BaseObject<TEntity, TKey> other = obj as BaseObject<TEntity, TKey>;
return BaseObjectEquals(other);
}
public override bool Equals(TEntity obj)
{
if (obj == null)
return false;
BaseObject<TEntity, TKey> other = obj as BaseObject<TEntity, TKey>;
return BaseObjectEquals(other);
}
public virtual bool BaseObjectEquals(BaseObject<TEntity, TKey> other)
{
if (other == null)
return false;
return EqualityComparer<TKey>.Default.Equals(this.Id , other.Id);
}
private IEnumerable<FieldInfo> GetFields()
{
Type t = GetType();
List<FieldInfo> fields = new List<FieldInfo>();
while (t != typeof(object))
{
fields.AddRange(t.GetTypeInfo().DeclaredFields.Where(x => x.FieldType.Name != typeof(ICollection<>).Name));//.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public));
t = t.GetTypeInfo().BaseType;
}
return fields;
}
public static bool operator ==(BaseObject<TEntity, TKey> x, BaseObject<TEntity, TKey> y)
{
// If both are null, or both are same instance, return true.
if (System.Object.ReferenceEquals(x, y))
{
return true;
}
// If one is null, but not both, return false.
if (((object)x == null) || ((object)y == null))
{
return false;
}
return x.Equals(y);
}
public static bool operator !=(BaseObject<TEntity, TKey> x, BaseObject<TEntity, TKey> y)
{
return !(x == y);
}
}
as #Panagiotis Kanavos stated, problem is in NHibernate overwrite of my property with a Set collection. I changed the map to Bag to make it work
I have several classes with id property of the same type int?:
public class Person {
public int? id { get; set; }
}
public class Project {
public int? id { get; set; }
}
// etc...
When writing code it happened that I compared semantically wrong types:
if (person.id == project.id), and of course there was no warning until I found the bug.
How could I create some kind of underlying type enforcement, or even better, a compiler warning, or something like that, that warns me not everything looks o.k.?
I can think of creating an Equals(Person p) { return p.id == this.id } but I'd prefer some other mechanism that could be used more 'freely'.
You need to override Equals and GetHashCode to be able to compare objects directly.
Try like this:
public sealed class Person : IEquatable<Person>
{
private readonly int? _id;
public int? Id { get { return _id; } }
public Person(int? id)
{
_id = id;
}
public override bool Equals(object obj)
{
if (obj is Person)
return Equals((Person)obj);
return false;
}
public bool Equals(Person obj)
{
if (obj == null) return false;
if (!EqualityComparer<int?>.Default.Equals(_id, obj._id)) return false;
return true;
}
public override int GetHashCode()
{
int hash = 0;
hash ^= EqualityComparer<int?>.Default.GetHashCode(_id);
return hash;
}
public override string ToString()
{
return String.Format("{{ Id = {0} }}", _id);
}
public static bool operator ==(Person left, Person right)
{
if (object.ReferenceEquals(left, null))
{
return object.ReferenceEquals(right, null);
}
return left.Equals(right);
}
public static bool operator !=(Person left, Person right)
{
return !(left == right);
}
}
public sealed class Project : IEquatable<Project>
{
private readonly int? _id;
public int? Id { get { return _id; } }
public Project(int? id)
{
_id = id;
}
public override bool Equals(object obj)
{
if (obj is Project)
return Equals((Project)obj);
return false;
}
public bool Equals(Project obj)
{
if (obj == null) return false;
if (!EqualityComparer<int?>.Default.Equals(_id, obj._id)) return false;
return true;
}
public override int GetHashCode()
{
int hash = 0;
hash ^= EqualityComparer<int?>.Default.GetHashCode(_id);
return hash;
}
public override string ToString()
{
return String.Format("{{ Id = {0} }}", _id);
}
public static bool operator ==(Project left, Project right)
{
if (object.ReferenceEquals(left, null))
{
return object.ReferenceEquals(right, null);
}
return left.Equals(right);
}
public static bool operator !=(Project left, Project right)
{
return !(left == right);
}
}
I also implemented IEquatable<Person> and == and != for good measure.
Now you can write person1 == this if this is a Person, but you would have a compiler error if this were a Project.
This is what tests are for. This is why you should write tests. Tests should pick up on these kind of errors.
But if you really want to go overkill, create a custom struct to store your IDs:
public struct Id<T> {
public int? ID { get; }
public static implicit operator Id<T>(int id) {
return new Id<T>(id);
}
public Id(int? id) { ID = id; }
public static bool operator ==(Id<T> lhs, Id<T> rhs) {
return lhs.ID == rhs.ID;
}
public static bool operator !=(Id<T> lhs, Id<T> rhs) {
return lhs.ID != rhs.ID;
}
}
// usage:
public class Person {
public Id<Person> Id { get; set; }
}
public class Project {
public Id<Project> Id { get; set; }
}
Whenever you try to compare Person.Id with Project.Id, the compiler will give you an error because you are comparing Id<Project> and Id<Person>.
Following problem:
In the definition of an function of a generic parent class ParentA I want to call an overloaded operator from ChildB:
See the following structure
class ParentA<T> where T : ParentB
{
public bool Contains(T element)
{
T element2;
return element==element2;
}
}
class ChildB : ParentB
{
public static bool operator ==(ChildB s1, ChildB s2)
{
//this one should be used
}
}
ChildA :ParentA<ChildB>
{
//make use of inherited function Contains(ChildB element)
}
I want to call the overloaded == operator of ChildB, but instead when I call the Contains function in ChildA the original ==operator from ParentB will be called.
Any idea how to make this work?
The Original code is a bit more nasty
public abstract class ElementBase
{
protected Element element;
public Element Element
{
get { return element; }
set { element = value; }
}
public static bool operator ==(ElementBase e1, ElementBase e2)
{
return e1.element == e2.element;
}
public static bool operator !=(ElementBase e1, ElementBase e2)
{
return e1.element != e2.element;
}
public override bool Equals(object obj)
{
if ((obj == null) || !this.GetType().Equals(obj.GetType()))
return false;
else
{
ElementBase element = (ElementBase)obj;
return this == element;
}
}
}
public class Structure : ElementBase
{
public bool flag;
public static bool operator ==(Structure s1, Structure s2)
{
return s1.element == s2.element && s1.flag==s2.flag;
}
public static bool operator !=(Structure s1, Structure s2)
{
return s1.element != s2.element || s1.flag!=s2.flag;
}
public override bool Equals(object obj)
{
if ((obj == null) || !this.GetType().Equals(obj.GetType()))
return false;
else
{
Structure structure = (Structure)obj;
return this == structure;
}
}
}
public class MapBase<T> where T : ElementBase
{
protected Dictionary<long, T> elements = new Dictionary<long, T>();
public bool Contains(T element)
{
...
return element==elements[id];
}
}
public class StructureMap : MapBase<Structure>
{
void someFunction()
{
//make use of Contains(Structure element)
}
}
Update
I replaced
return element==element2;
by
return element.Equals(element2);
and now it seems like it does the trick. I just don't understand why...
Lets say I define the following abstract class:
public abstract class ValueEquality<T> : IEquatable<T>
where T : ValueEquality<T>
{
public override bool Equals(object obj)
{
return Equals(obj as T);
}
public static bool operator ==(ValueEquality<T> lhs, object rhs)
{
if (ReferenceEquals(lhs, rhs))
{
return true;
}
else if (ReferenceEquals(lhs, null) || ReferenceEquals(rhs, null))
{
return false;
}
else
{
return lhs.Equals(rhs);
}
}
public static bool operator !=(ValueEquality<T> lhs, object rhs)
{
return !(lhs == rhs);
}
public bool Equals(T other)
{
return other != null && EqualNoNull(other);
}
public abstract override int GetHashCode();
public abstract bool EqualNoNull(T other);
}
And then create a class C as follows:
public class C : MyEquatable<C>
{
public override bool EqualsNoNull(C other)
{
...
}
public override int GetHashCode()
{
...
}
}
If I then have the code:
C x1;
C x2;
bool equal = x1 == x2;
Will this end up calling the equals method in C? Are there any gotchas with this approach?
Edit: fixed some issues in code raised by answers.
This code will do infinite loop in:
public override bool Equals(object obj)
{
try
{
T otherT = (T) obj;
return Equals(this, otherT);
}
catch (InvalidCastException)
{
return false;
}
}
It will call Equals(object obj) again and again. Right implementation:
public abstract class MyEquatable<T> : IEquatable<T>
where T : MyEquatable<T>
{
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != this.GetType())
{
return false;
}
return this.Equals((MyEquatable<T>)obj);
}
protected bool Equals(MyEquatable<T> other)
{
return this.Equals(other as T);
}
public static bool operator ==(MyEquatable<T> lhs, object rhs)
{
return Equals(lhs, rhs);
}
public static bool operator !=(MyEquatable<T> lhs, object rhs)
{
return Equals(lhs, rhs);
}
public abstract bool Equals(T other);
public abstract override int GetHashCode();
}
x1 == x2 will call operator == of MyEquatable, that will call Equals(object obj). Finally, it calls Equals(T other) overridden in C class
Another implementation which follows what is usually advised in documentation
public abstract class MyEquatable<T> : IEquatable<T>
where T : MyEquatable<T> {
public override bool Equals(object obj) {
if (ReferenceEquals(obj, null) || obj.GetType() != GetType())
return false;
var valueObject = obj as T; //Note the cast
if (ReferenceEquals(valueObject, null))
return false;
return Equals(valueObject); //Calls Equals(T other)
}
public abstract bool Equals(T other);
public abstract override int GetHashCode();
public static bool operator ==(MyEquatable<T> left, MyEquatable<T> right) {
if (ReferenceEquals(left, null) && ReferenceEquals(right, null))
return true;
if (ReferenceEquals(left, null) || ReferenceEquals(right, null))
return false;
return left.Equals(right);
}
public static bool operator !=(MyEquatable<T> left, MyEquatable<T> right) {
return !(left == right);
}
}