按普通用户ID linq对两个列表进行分组

时间:2019-12-09 19:33:16

标签: c# linq

我有两个列表

相册和照片

我想将它们组合在一起,以便每个相册将包含分配给该相册的所有照片,并仅返回定义了用户ID的相册

class Album{
 Id
 UserId
}

class Photo{
 Id
 AlbumId

}


    albums.Add(new Album { Id = 1, Photos = null, Title = "Summer", UserId = 1 });
    albums.Add(new Album { Id = 2, Photos = null, Title = "Winter", UserId = 1 });
    albums.Add(new Album { Id = 3, Photos = null, Title = "Spring", UserId = 2 });

我已尝试关注,但这会返回所有专辑,我想念什么?

  var result = (from album in albums
                          join photo in photos on album.Id equals photo.AlbumId
                          where album.UserId == 1
                          select new Album
                          {
                              Id = album.Id,
                              Title = album.Title,
                              UserId = album.UserId,
                              Photos = photos.Where(p => p.AlbumId == album.Id)
                          }).ToList().AsEnumerable();

2 个答案:

答案 0 :(得分:1)

尝试一下:

var groupedAlbums = albums
    .GroupJoin(photos,
        a => a.Id,
        p => p.AlbumId,
        (a, p) => new
        {
            AlbumId = a.Id,
            UserId = a.UserId,
            Title = a.Title,
            Photos = p.Select(pp => pp).ToList()
        })
        .Where(a => a.Photos.Any())
        .Where(a => a.UserId == 1);

答案 1 :(得分:0)

我是简单的忠实拥护者,所以除非我缺少明显的东西,否则

        var here = albums.Where(a => a.UserId == 1).Select(b => new Album
            {
                Id = b.Id,
                Title = b.Title,
                UserId = b.UserId,
                Photos = photos.Where(a => a.AlbumId == b.Id).ToList()
            }).ToList();