I know it's very strange but I don't find another way to say it. Please see the image below
The output is 1 and always it's the same!
I really don't understand what happend here. Can anyone explain to me?
I know it's very strange but I don't find another way to say it. Please see the image below
The output is 1 and always it's the same!
I really don't understand what happend here. Can anyone explain to me?
Just a couple of observations on your Modelo
and Medicion
classes:
public class Modelo<T>
{
// 1) note PROTECTED set on Id
public virtual int Id { get; protected set; }
public override bool Equals(object obj)
{
...
// 2) comparison is based on Id
return (this == obj || this.Id == specificOject.Id);
}
...
}
public class Medicion : Modelo<Medicion> {...}
Id
member is defined as protected set
.Equals
method defines two objects as the same if the Id
in both are the same.Are you setting the Id
of your Medicion
objects anywhere? If not, they are likely to all be 0
. If all the Ids are the same, this makes all your objects look the same (your equality definition is based on Id
).
Therefore, Mediciones.Contains
will always be true
after the first object is added. You don't provide any info on Mediciones
, but I am assuming here that it is a standard List
with no overrides.
One of those intellisense dialogs is showing you TodasMediciones. The other is showing you Mediciones. These are not the same value.
See Modify List.Contains behavior
You're going to want to implement IEquatable<T>
in your Medicion
.
I don't understand what is your problem. The loop loops on TodasMediciones which is a List. The second debugger is on Mediciones. Both are different objects.
Well I'm wrong. The problem (I don't know why) is !Mediciones.Contains(m)
. The first time is false and in the next iterations is true.
I change method as follow
public virtual void AddMediciones(List<Medicion> TodasMediciones)
{
int i = 0;
foreach (Medicion m in TodasMediciones)
{
Console.WriteLine(Mediciones.Contains(m));
Console.WriteLine(m.Valor);
Console.WriteLine("-------------------------------------------");
if (!Mediciones.Contains(m))
{
Mediciones.Add(m);
}
}
}
Their output is:
False
1
-------------------------------------------
True
2
-------------------------------------------
True
3
-------------------------------------------
True
4
-------------------------------------------
Here is the Medicion definition:
public class Medicion : Modelo<Medicion>
{
public virtual DateTime Fecha { get; set; }
public virtual decimal Valor { get; set; }
public virtual Indicador Indicador { get; set; }
}
}
And their parent definition
public class Modelo<T>
{
public virtual int Id { get; protected set; }
public override bool Equals(object obj)
{
if (obj == null || obj.GetType() != this.GetType())
{
return false;
}
Modelo<T> specificOject = (Modelo<T>)obj;
return (this == obj || this.Id == specificOject.Id);
}
public override int GetHashCode()
{
return Id.GetHashCode() ^ 5;
}
}