更好的方法
using (var db = new SmartContext())
{
var MyQuery = from idr in db.ID_SB
join tk in db.Track_SB on idr.MB_Track_ID equals tk.MB_TrackID
join talr in db.Track_Album_Reln on tk.MB_TrackID equals talr.MB_Track_ID
join tal in db.Album_SB on talr.MB_AlbumID equals tal.MB_Release_ID
orderby idr.Last_played descending
select new
{
mb = tk.MB_TrackID,
Hash = idr.Hash,
Title = tk.Title,
Album = tal.Album_Name,
Times_Played = idr.Times_played,
Last_Played = idr.Last_played
};
string artist = "";
var list = new[] { new { Hash = "", Title = "", Album = "", Artist = "", Times_Played = "", Last_Played = ""}}.ToList();
list.Clear();
foreach (var q in MyQuery)
{
int i = 0;
var art = db.Track_Artist_Reln.Where(a => a.MB_Track_ID == q.mb);
foreach (var a in art)
{
var tart = db.Artist_SB.Where(ar => ar.MB_Artist_ID == a.MB_ArtistID).Select(ar => ar.Artist_Name);
foreach (var tar in tart)
{ if (i != 0) { artist = artist + ", " + tar; } else { artist = tar; i++; } }
}
list.Add(new
{
Hash = q.Hash.ToString(),
Title = q.Title.ToString(),
Album = q.Album.ToString(),
Artist = artist.ToString(),
Times_Played = q.Times_Played.ToString(),
Last_Played = q.Last_Played.ToString(),
});
}
ListView1.ItemsSource = list;
}
有没有更好的方法,因为它消耗了大量的时间
此代码用于 p>目的
在此我想要检索
通过加入除艺术家名称之外的所有东西,我能够获得的一切
可能有许多关系 主表ID_SB,Track_SB,Album_SB,Artist_SB 另一种是存储两个表的主键的关系答案 0 :(得分:0)
可以使用string.Join(…)
和.SelectMany()
替换内部循环,以将嵌套列表(真正IEnumerable
)展平为一个:
var artist = string.Join(", ",
db.Track_Artist_Reln
.Where(a => a.MB_Track_ID == q.mb)
.SelectMany(a => db.Artist_SB
.Where(ar => ar.MB_Artist_ID == a.MB_ArtistID)
.Select(ar => ar.Artist_Name)));
您可以使用.ToList()
:
var list = MyQuery.Select(q => new{
Hash = q.Hash.ToString(),
Title = q.Title.ToString(),
Album = q.Album.ToString(),
Artist = string.Join(", ",
db.Track_Artist_Reln
.Where(a => a.MB_Track_ID == q.mb)
.SelectMany(a => db.Artist_SB
.Where(ar => ar.MB_Artist_ID == a.MB_ArtistID)
.Select(ar => ar.Artist_Name))),
Times_Played = q.Times_Played.ToString(),
Last_Played = q.Last_Played.ToString(),
}.ToList();