I’m trying to remove duplicate entries from a list which contains a generic 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 the dupes:
IEnumerable<MessageInfo> new_texts = text_messages.Distinct(new SMSDupeRemover());
The problem is Equals and GetHashCode is never called. Anyone have any idea why?
Because
Distinctis lazy. Try to addToList()at the end.Longer answer. Linq operations are actually declarative ones. They define query, but they do not tell to execute it.
IEnumerable<T>doesn’t contain data, just query definition. You have constructed query, okay, how to get data?foreachtheIEnumerable. Sinceforeachis imperative all data must be retrieved (query executed).ToList/ToDictionary. Those collections store real data so in order to populate them system has to execute query.