c#列表继承

本文关键字:继承 列表 | 更新日期: 2023-09-27 17:50:58

我正在写一个处理歌曲的c#程序。我有一个Song类和一个继承Song类型列表的SongCollection类。我需要写一个方法,接受一个艺术家(字符串)作为它的参数,我需要返回艺术家的一个新的SongCollection。我找歌单有点困难。

public SongCollection GetAllByArtist(string artist)
{
        SongCollection newSongs = new SongCollection();
        if (this.Artist == artist)
        {
            newSongs.Add(this.Song);
        }
        return newSongs;
}

c#列表继承

这应该可以为您工作:

 public SongCollection GetAllByArtist(string artist)
 {
    SongCollection newSongs = new SongCollection();
    newSongs.AddRange(this.Where(p=>p.Artist == artist))        
    return newSongs;
 }

您需要遍历集合并对每首歌进行艺人检查,而不是对列表本身进行检查:

public SongCollection GetAllByArtist(string artist)
{
        SongCollection newSongs = new SongCollection();
        foreach (Song s in this) {
            if (s.Artist == artist)
            {
                newSongs.Add(s);
            }
        }
        return newSongs;
}