duck
duck

Reputation: 867

Simple IEqualityComparer<T> question

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?

Upvotes: 8

Views: 560

Answers (4)

Daniel Mošmondor
Daniel Mošmondor

Reputation: 19956

I would do

List<MessageInfo> unique_msgs = 
    new List(text_messages.Distinct(new SMSDupeRemover()));

to immediately render the new list. Unless you really need enumerator, to conserve the memory.

Upvotes: 1

foson
foson

Reputation: 10227

The IEqualityComparer isn't called until the IEnumerable is enumerated.

Try

var new_texts = text_messages.Distinct(new SMSDupeRemover()).ToList();

Upvotes: 2

Cory Nelson
Cory Nelson

Reputation: 30001

LINQ is lazily evaluated, so that won't execute until you call GetEnumerator and possibly even MoveNext.

Try adding a .ToList() to the end of that query and it should execute right away.

Upvotes: 2

Andrey
Andrey

Reputation: 60065

Because Distinct is lazy. Try to add ToList() 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?

  • foreach the IEnumerable. Since foreach is imperative all data must be retrieved (query executed).
  • Call ToList/ToDictionary. Those collections store real data so in order to populate them system has to execute query.

Upvotes: 12

Related Questions