Simple Question IEqualityComparer <T>
I am trying to remove duplicate entries from a list that contains a shared object.
public class MessageInfo { public DateTime Date { get; set; } public string To { get; set; } public string Message { get; set; } } public class SMSDupeRemover : IEqualityComparer<MessageInfo> { public bool Equals(MessageInfo x, MessageInfo y) { throw new NotImplementedException(); } public int GetHashCode(MessageInfo obj) { throw new NotImplementedException(); } } And the code to remove duplicates:
IEnumerable<MessageInfo> new_texts = text_messages.Distinct(new SMSDupeRemover()); Problem: Equals and GetHashCode are never called. Does anyone know why?
Because Distinct lazy. Try adding ToList() to the end.
Longer answer. Linq's operations are actually declarative. They define the request, but they do not say to fulfill it. IEnumerable<T> contains no data, just a request definition. You created a query, ok, how to get the data?
foreachIEnumerable. Sinceforeachis required, all data must be restored (request completed).- Call
ToList/ToDictionary. These collections store real data, so the system must complete the request to fill them.
LINQ is lazily evaluated, so it won’t run until you name GetEnumerator and possibly even MoveNext .
Try adding .ToList() to the end of this query, and it should execute right away.
IEqualityComparer is not called until IEnumerable is listed.
Try
var new_texts = text_messages.Distinct(new SMSDupeRemover()).ToList(); I would do
List<MessageInfo> unique_msgs = new List(text_messages.Distinct(new SMSDupeRemover())); to immediately display the new list. Unless you really need an enumerator to save memory.