- Home /
Comparing list values
Hi guys! So I need your help, I have created this list, and I'm trying to avoid inserting duplicated values. I've already tried some options but this isn't going that well. So it would be awesome if you could lend me a hand!
So here it goes the list class
public class Eating_Progress : IComparable<Eating_Progress>
{
public int Fruit_X;
public int Fruit_Y;
public int Fruit_Z;
public Eating_Progress(int F_X, int F_Y, int F_Z)
{
Fruit_X = F_X;
Fruit_Y = F_Y;
Fruit_Z = F_Z;
}
public int CompareTo(Eating_Progress other)
{
if(other == null)
{
return 1;
}
return Fruit_Z - other.Fruit_Z;
}
}
and here's what I'm trying to do
public List<Eating_Progress> eating_progress;
void Start () {
int log_ = 0;
eating_progress = new List<Eating_Progress>();
eating_progress.Add(new Eating_Progress(1, 1, 1));
eating_progress.Add(new Eating_Progress(2, 2, 2));
eating_progress.Add(new Eating_Progress(3, 3, 3));
eating_progress.Add(new Eating_Progress(4, 4, 4));
eating_progress.Add(new Eating_Progress(1, 2, 3));
// Checks if there's already that value
if (!eating_progress.Contains(new Eating_Progress(1,2,3)))
{
eating_progress.Add(new Eating_Progress(1, 2, 3));
}
foreach (Eating_Progress Fruit_X in eating_progress)
{
log_++;
Debug.Log(log_);
}
}
Well for some reason this doesn't really do what I want to do, and just adds that value :/
So thanks for your help! Cheers
Answer by landon912 · Oct 15, 2015 at 07:13 PM
@Costa_GP Good question.
You see, in this line:
if (!eating_progress.Contains (new Eating_Progress (1, 2, 3)))
You're actually passing a (new) reference into the IContainer.Contains()
method. In all actuality, it is impossible for a new reference to be equal to an existing reference. Therefore, we must compare the actual contents of the Eating_Progress
class to another instead of simply comparing their reference.
How? Well, in checking if the List<>
contains an object, the method calls IEquatable.Equals()
on both objects. Therefore, we can override that method to compare the important contents of the class instead of their reference.
public class Eating_Progress : IComparable<Eating_Progress>, IEquatable<Eating_Progress>
{
public int Fruit_X;
public int Fruit_Y;
public int Fruit_Z;
public Eating_Progress(int F_X, int F_Y, int F_Z)
{
Fruit_X = F_X;
Fruit_Y = F_Y;
Fruit_Z = F_Z;
}
public int CompareTo(Eating_Progress other)
{
return other == null ? 1 : Fruit_Z - other.Fruit_Z;
}
public bool Equals (Eating_Progress other)
{
return (Fruit_X == other.Fruit_X && Fruit_Y == other.Fruit_Y && Fruit_Z == other.Fruit_Z);
}
}
Right, CompareTo is used when sorting the list. CompareTo just returns if one element is higher, lower or equal in regard to the sorting order.