У меня есть следующая иерархия классов:
abstract class Product : IComparable
{
public string Name { get; set; }
public decimal Price { get; set; }
public string Barcode { get; set; }
public int CompareTo(object obj)
{
int ret = -1;
if (String.Compare(this.GetType().Name, obj.GetType().Name,StringComparison.Ordinal) == 0)
ret = 0;
return ret;
}
}
abstract class Book : Product
{
public int PagesCount { get; set; }
}
class ProgrammingBook : Book
{
public string ProgrammingLanguage { get; set; }
}
class CulinaryBook : Book
{
public string MainIngridient { get; set; }
}
class EsotericBook : Book
{
public int MininumAge { get; set; }
}
abstract class Disc : Product
{
internal enum Content
{
Music,
Video,
Software
}
public Content DiscContent { get; set; }
}
class CdDisc : Disc
{
}
class DvdDisc : Disc
{
}
И я пытаюсь отсортировать следующую коллекцию с помощью метода интерфейса IComparable CompareTo:
List<Product> products = new List<Product>
{
new DvdDisc {Name = "The lord of the rings 2",DiscContent = Disc.Content.Video,Price = 200M,Barcode = "5435443-2"},
new CdDisc {Name = "Antonio Vivaldi: best picks",Price = 700M, DiscContent = Disc.Content.Music,Barcode = "4543765-565"},
new CulinaryBook{Name = "Midterranian foods",MainIngridient = "Salmon",PagesCount = 436,Price = 350M,Barcode = "41457561-897"},
new CdDisc{Name = "Windows XP", DiscContent = Disc.Content.Software, Price = 950M, Barcode = "5433668-4"},
new EsotericBook{Name = "Russian Freemasonry 1731-2000",MininumAge = 21,PagesCount = 2100,Price = 3000M,Barcode = "6464632-876"},
new CdDisc {Name = "The best of Mussorgsky",Price = 300M, DiscContent = Disc.Content.Music,Barcode = "5435436-567"},
new ProgrammingBook{Name = "CLR via C#",PagesCount = 900, Price = 1110M,ProgrammingLanguage = "C#",Barcode = "5546533-2446"},
new DvdDisc {Name = "The lord of the rings 1",DiscContent = Disc.Content.Video,Price = 200M,Barcode = "54354423-2"},
new ProgrammingBook{Name = "ASP.NET MVC 4",PagesCount = 800,Price = 1200M,ProgrammingLanguage = "C#",Barcode = "46476573-65"},
new EsotericBook{Name = "Russian Freemasonry in it's future and past",MininumAge =19, PagesCount = 900, Price = 2342M,Barcode = "3656353-24"},
new CulinaryBook{Name = "Traditional Polish dishes",MainIngridient = "Red meat",PagesCount = 630,Price = 840,Barcode = "54634234-5"}
}; products.Sort();
Выходной список должен выглядеть так:
1.1 Книги по программированию
1.2 Книги по кулинарии
1.3 Книги по эзотерике
2.1 CD-диски, отсортированные по содержимому
2.2 DVD-диски, отсортированные по содержимому
Мой текущий метод CompareTo выполняет только часть работы — сравнивает классы по имени.