zaza
zaza

Reputation: 912

C# LINQ Distinct(IEqualityComparer) help

I have a generic list where the user can add files. I'm trying to get it to delete an object if the source already exists in another object in the list. I will also mention that I'm new to using the features of System.Linq.

The list if of type MediaInfo:

public static List<MediaInfo> imagePlaylist = new List<MediaInfo>();

This is the code for the MediaInfo struct and the IEqualityComparer:

public struct MediaInfo
{
    public string source;
    public char? type;        
}
public class MediaInfoComparer : IEqualityComparer<MediaInfo>
{
    public bool Equals(MediaInfo x, MediaInfo y)
    {
        return Convert.ToBoolean(string.Compare(x.source, y.source, true));

    }

    public int GetHashCode(MediaInfo obj)
    {
        if (Object.ReferenceEquals(obj, null)) return 0;
        int hashProductName = obj.source == null ? 0 : obj.source.GetHashCode();
        int hashProductCode = obj.type.GetHashCode();
        return hashProductName ^ hashProductCode;
    }
}

I don't understand why the Distinct(IEqualityComparer) is not working.

imagePlaylist = imagePlaylist.Distinct(new MediaInfoComparer()).ToList();

Thanks,

Upvotes: 2

Views: 3322

Answers (2)

The Scrum Meister
The Scrum Meister

Reputation: 30111

The IEqualityComparer logic is backwards:

string.Compare will return 0 when 2 strings are equal.

Convert.ToBoolean will return false when the parameter is 0.

Upvotes: 1

Tejs
Tejs

Reputation: 41246

String compare returns Negative, 0, or positive; it's not a boolean operation. See this link for details. So you would have two situations where it returns false, and one where it returns true. In addition, the situation where it returns true is when the strings aren't actually the same.

Basically, what you need to do is this:

return string.Compare(x.source, y.Source, true) == 0;

Upvotes: 3

Related Questions