循环在每次迭代时清空模型内容



我知道我在这里错过了一些基本的东西。我有一个嵌套循环序列来过滤掉添加到特定播放列表的一组专辑中的歌曲。这是我的代码:

foreach (var item in model.Albums)
{
    foreach (var song in model.PlaylistSongs)
    {
        model.Songs = item.Songs.Where(x => x.SongID == song.SongID).ToList();
        foreach (var single in model.Songs)
        {
            System.Diagnostics.Debug.WriteLine("Loop");
            System.Diagnostics.Debug.WriteLine(single.Album.AccountInfo.DisplayName);
        }
    }
}

哪里:

model.Albums is List<Albums> // albums identified with a song used in the playlist
model.PlaylistSongs is List<PlaylistSongs> // list of all songs found in specific playlist
model.Songs is List<Songs> // resultant model

我有一个调试循环来显示附加model.Songs的内容。它应该显示如下内容:

Loop
Koda
Loop
Koda
Danrell
Loop
Koda
Danrell
Attom

但是,我所看到的只是这个,因此模型在每次迭代时都会被擦除:

Loop
Koda
Loop
Danrell
Loop
Attom

有没有办法附加?我尝试了model.Songs.Add(item.Songs.Wherex => x.SongID == song.SongID).ToList())但它给了我一个例外Cannot convert from System.Collections.Generic.List<Domain.Data.Song> to Doman.Data.Song.

您正在分配给 Songs 属性,而不是添加到它。因此,每个循环都会获得一个新的副本。

而不是

model.Songs = item.Songs.Where(x => x.SongID == song.SongID).ToList();

尝试

model.Songs.AddRange(item.Songs.Where(x => x.SongID == song.SongID));

这是让你工作起来的最小变化。请注意,您必须在开始循环之前实例化列表,例如 model.Songs = new List<Song>() .

如果它要充分发挥 LINQ 的潜力,您应该摆脱循环,让 LINQ 为您完成。

而不是:

foreach (var item in model.Albums)
{
    foreach (var song in model.PlaylistSongs)
    {
        model.Songs = item.Songs.Where(x => x.SongID == song.SongID).ToList();
        foreach (var single in model.Songs)
        {
            System.Diagnostics.Debug.WriteLine("Loop");
            System.Diagnostics.Debug.WriteLine(single.Album.AccountInfo.DisplayName);
        }
    }
}

试试这个:

model.Songs = model.Albums
    .SelectMany       //Combine all albums songs into one list
    (
        a => a.Songs 
    )
    .Where           //Only take those that are in the playlist
    (
        s => model.PlaylistSongs.Any
        ( 
            p => p.SongID == s.SongID 
        )
    )
    .ToList();
foreach (var single in model.Songs)
{
    Debug.WriteLine(single.Album.AccountInfo.DisplayName);
}

最新更新