I have trouble deleting the duplicate references in my list.
I have this list
List<SaveMongo> toReturn
with my class SaveMongo that looks like this
public class SaveMongo
{
public ObjectId _id { get; set; }
public DateTime date { get; set; }
public Guid ClientId { get; set; }
public List<TypeOfSave> ListType = new List<TypeOfSave>();
public List<ObjectId> ListObjSave = new List<ObjectId>();
public SaveMongo()
{ }
}
Whenever I want to add an element to my list I use the following code
public static fctName(BsonDocument doc)
{
toReturn.Add(AddingSaveMongo(doc.GetValue("_id")));
}
public static SaveMongo AddingSaveMongo(BsonValue ObjValue)
{
foreach (SaveMongo doc in SpeCollection.FindAll())
{
foreach (var id in doc.ListObjSave)
{
if (id == ObjValue)
return (doc);
}
}
return (null);
}
However, I sometimes get duplicates references. I tried using this
toReturn = toReturn.Distinct().ToList();
to delete them. Without success.
I also tried to do this
if (!toReturn.Contains(AddingSaveMongo(doc.GetValue("_id"))))
toReturn.Add(AddingSaveMongo(doc.GetValue("_id")));
Still without success. But whenever I print the references in my list I get those result
What I am missing here so that I still have duplicates references in my List ?
Currently, Distinct
is matching your objects using object.Equals
, which is doing reference equality. One way to tell it to match objects based on other criteria is by implementing IEquatable<SaveMongo>
. This example compares objects based on their Id
:
public class SaveMongo : IEquatable<SaveMongo>
{
public ObjectId _id { get; set; }
public DateTime date { get; set; }
public Guid ClientId { get; set; }
public List<TypeOfSave> ListType = new List<TypeOfSave>();
public List<ObjectId> ListObjSave = new List<ObjectId>();
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 Equals((SaveMongo) obj);
}
public override int GetHashCode()
{
return _id.GetHashCode();
}
public bool Equals(SaveMongo other)
{
return _id.Equals(other._id);
}
}
Use grouping:
toReturn = (from e in toReturn
group e by e._id into g
select g.First()).ToList();
Also, you can group by two (or more) fields:
toReturn = (from e in toReturn
// group by ID and Date component
group e by new { e._id, e.date.Date } into g
select g.First()).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With