2

I have following tables

**Track Table**
+---------------+---------------+--------------------+
| TrackId        | TrackName    |       Path         |
+===============+===============+====================+
| 1             | jb            | http://domain/1.mp3|
+---------------+---------------+--------------------+
| 2             | remix         | http://domain/2.mp3|
+---------------+---------------+--------------------+

**Favorite Table**
    +---------------+---------------+--------------------+
    | favoriteId    | ProfileId     |       TrackId      |
    +===============+===============+====================+
    | 10            | 2130          | 1                  |
    +---------------+---------------+--------------------+
    | 11            | 2132          | 2                  |
    +---------------+---------------+--------------------+

I need to select tracks into a model where I have to include a boolean field IsFavorite. Right now my logic is as follows:

1.Select Tracks
2.Select all favorites by profile
3.Iterate to both list and fill field "IsFavorite"

Is there any better method that can work out the same?

Following is my current logic code

Var ActiveTracks = jukeboxTrackService.GetActiveTracks();
var UserFavorites = jukeboxTrackService.GetFavoritesByProfile(ProfileId);
foreach (var item in ActiveTracks )
{
    foreach (var fav in UserFavorites)
    {
        if (item.JukeBoxTrackId == fav.TrackId)
        {
            item.IsFavorite = true;
        }
    }
}

return ActiveTracks ;

Thanks in advance.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
Siraj E A
  • 65
  • 1
  • 6

1 Answers1

2
(from tr in ActiveTracks 
join usrfav in UserFavorites on tr.TrackId equals usr.TrackId into UsrTracks
from usrtr in  UsrTracks.DefaultIfEmpty()
select new Track
{ 
  IsFavorite = (usrfav.TrackId == null) ? false : true 
}
Karthikeyan
  • 347
  • 3
  • 8