我知道我在这里缺少一些基本的东西。我有一个嵌套的循环序列来过滤掉添加到特定播放列表的一组专辑中的歌曲。这是我的代码:
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.
答案 0 :(得分:4)
您正在分配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);
}