C# - Collection.Distinct() and Generics question...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • manwood
    New Member
    • Feb 2008
    • 2

    C# - Collection.Distinct() and Generics question...

    I have a generic method that performs some basic sorting and removal of duplicates on some classes, but I cannot get the parameter to pass into the Distinct function working.

    This is my class code that implements IEqualityCompar er<T>:

    Code:
        public class Artist : IEqualityComparer<Artist>
        {
            public Artist()
            {
            }
    
            public Artist(string name)
            {
                this.Name = name;
            }
    
            private string _name;
            public string Name
            {
                get { return _name; }
                set { _name = value; }
            }
    
            #region IEqualityComparer Members
    
            public CaseInsensitiveComparer comparer = CaseInsensitiveComparer.Default;
    
            public bool Equals(Artist x, Artist y)
            {
                if (comparer.Compare(x.Name, y.Name) == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
    
            public int GetHashCode(Artist obj)
            {
                return obj.ToString().ToLower().GetHashCode();
            }
    
            #endregion
        }
    this is the generic method that performs a sort and removal of duplicates of Artist (and other classes):

    Code:
            public static IEnumerable<T> CreateTypeCollection<T>(AudioFileCollection files, Func<AudioFile, T> mapFunc, Func<T, string> orderFunc) where T : IEqualityComparer<T>
            {
                Collection<T> collection = new Collection<T>();
                foreach (AudioFile file in files)
                {
                    collection.Add(mapFunc(file));
                }
                return collection.Distinct(EqualityComparer<T>.Default).OrderBy(orderFunc);
            }
    and this is the method call:

    Code:
                _collection = LibraryBuilder.CreateTypeCollection<Artist>(AudioFileCollection, file => new Artist(file.Artist.ToLower()), artist => artist.Name);
    everything works fine apart from this bit:

    Code:
    collection.Distinct(EqualityComparer<T>.Default).
    i want to pass the 'Equals(Artist x, Artist y)' implementation into the Distinct() method but in a generic way. i cant get it working, any help is much appreciated.

    :)
Working...