Get information relevant to user using LINQ on Object list ( Combined lists )

89 Views Asked by At

I have a list of photos and a list of Albums. I created one single List of type object to combine them. Now I'm trying to use LINQ so that I can retrieve albums based on userId and the photos contained inside the album.

Could anyone help me in understanding how to retrieve the above?

I'm using LINQPAD in order to do that, so I will attach a photo here.

enter image description here

2

There are 2 best solutions below

4
Nguyễn Văn Phong On BEST ANSWER

You can not access the property from object type (Unless you use Reflection to get property value in c#). So that is the reason why you are getting the error.

If you want to retrieve albums based on userId and the photos contained inside the album, you can use linq to object like below

var result = (from p in _photos
             join a in _albums on p.AlbumId equals a.Id
             where a.UserId==1
             select new { p.Title, a.Title}).ToList();
// It returns `Anonymous type`

You can also create one class to store your value like below

public class Result
{
    public string AlbumTitle { get; set; }
    public string PhotoTitle { get; set; }
    public string Photo_ThumbnailUrl { get; set; }
    // Any properties as you wish
}

var result = (from p in _photos
                 join a in _albums on p.AlbumId equals a.Id
                 where a.UserId==1
                 select new Result { PhotoTitle = p.Title, AlbumTitle = a.Title, Photo_ThumbnailUrl = p.ThumbnailUrl}).ToList();
2
ocuenca On

What you need is a join:

var query= from photo in _photos
           join album in _albums on photo.AlbumId equals album.ID
           where album.UserId==1
           select new {album, photo};