Question List of objects - how to remove duplicates?

raysefo

Well-known member
Joined
Feb 22, 2019
Messages
361
Programming Experience
10+
Hi,

I have two entities as follows. I wonder if I can remove duplicates based on referenceId?

C#:
public class Recon
{
   public int id { get; set; }
   public DateTime? reconDateTime { get; set; } = DateTime.Now;
   public List<ReconDetail> ReconDetails { get; set; } = new List<ReconDetail>();
}

public class ReconDetail
{
   public int id { get; set; }
   public int ReconId { get; set; }
   public Guid referenceId { get; set; }
   public string status { get; set; } = "OK";
}
 
I think something like below works:
C#:
List<ReconDetail> duplicates = reconResponse.ReconDetails.Except(reconResponse.ReconDetails
                            .GroupBy(i => i.referenceId)
                            .Select(ss => ss.FirstOrDefault()))
                        .ToList();
 
Just use the Distinct<T>() extension method. Here would be a naive implementation.
C#:
class ReconDetailComparer : IEqualityComparer<ReconDetail>
{
    public bool Equals(ReconDetail a, ReconDetail b) => a.referenceId == b.referenceId;
    public int GetHashCode(ReconDetail a) => a?.referenceId.GetHashCode() ?? 0;
}
:
var noDupes = reconResponse.ReconDetails.Distinct(new ReconDetailComparer());
 
Back
Top Bottom