如何排序对象列表?订单c#

时间:2015-04-28 03:40:43

标签: c#

我有Track课程

class Track
{
    public String Name { get; set; }
    public Double Duration;
    public Boolean IsRemix;

    public override string ToString()
    {
        if (IsRemix) return Name + "(Remix) " + Duration;
        return Name + " " + Duration;
    }
}

Album是一个列表:

class Album :List<Track>
    {
        public Album SortByAlphabet()
        {
            return new Album().OrderBy(x=>x.Name);
        }
    }

如何按曲目名称订购相册?在SortByAlphabet中,我只需要输出Album。

修改

return this.OrderBy(x=>x.Name).ToList();

return (Album)this.OrderBy(x=>x.Name).ToList();

无效

它的
抛出异常,InvalidCastException

3 个答案:

答案 0 :(得分:2)

我不建议继承List,但如果你这样做,以下内容应符合你的要求:

class Album : List<Track>
{
    public Album() : base() { }

    public Album(IEnumerable<Track> tracks) : base(tracks) { }

    /// <summary>
    /// Sort in place the album of tracks alphabetically by name 
    /// </summary>
    public void SortByAlphabet()
    {
        Sort((t1, t2) => t1.Name.CompareTo(t2.Name));
    }

    /// <summary>
    /// Return a new Album with tracks sorted alphabetically by name.
    /// </summary>
    /// <returns></returns>
    public Album OrderByAlphabet()
    {
        return new Album(this.OrderBy(t => t.Name));
    }
}

答案 1 :(得分:2)

不要继承List<T>You aren't making a list, you're making an album

一张专辑有一个歌曲列表,你可以用一个成员来表示。它使用了Track的实现(我老实说,我没有使用BooleanDouble等,而且没有公共字段,但这是另一个讨论。)

class Album {
  private readonly List<Track> _tracklist;
  public ReadOnlyCollection<Track> Tracklist {
    get {
      return new ReadOnlyCollection<Track>(_tracklist);
    }
 }

  public Album(IEnumerable<Track> tracklist) {
    _tracklist = new List<Track>(tracklist);
  }
}

用法:

var album = new Album(new List<Track> {
  new Track { Name = "Blonde"}, 
  new Track { Name = "K.-O."}, 
  new Track { Name="Alcaline"}, 
  new Track { Name="Seulement pour te plaire"}, 
  new Track { Name="L'amour renfort"},
  new Track { Name="Bi"},
  new Track { Name="Mon planeur"},
  new Track { Name="Ce qui tue l'amour"},
  new Track { Name="Tweet"},
  new Track { Name="Charles est stone"},
  new Track { Name="Mylène Farmer"},
  new Track { Name="Plus de bye bye"}
});

var culture = new CultureInfo("fr-FR");
var tracks = album.Tracklist.OrderBy(t => t.Name, StringComparer.Create(culture, false));
tracks.ToList().ForEach(Console.WriteLine);

输出:

Alcaline 0
Bi 0
Blonde 0
Ce qui tue l'amour 0
Charles est stone 0
K.-O. 0
L'amour renfort 0
Mon planeur 0
Mylène Farmer 0
Plus de bye bye 0
Seulement pour te plaire 0
Tweet 0

答案 2 :(得分:-2)

试试这个

class Album : List<Track>
{
    public Album SortByAlphabet()
    {
        return (Album)(this.OrderBy(o => o.Name).ToList());
    }
}