Creating object hierarchies with LINQ

I’m constantly amazed by the power and simplicity of LINQ.  I love that I can turn a flat table into a  object graph with a couple of view models and a single LINQ query.

Given a repository method that returns a list of Tracks based on the following SQL:

Select Id, Title, Artist, Album, Year, TrackNumber, FilePathName From Track Order By Artist, Album, TrackNumber, Title

We can create a nice hierarchy of  Artists, each with 0 or more albums, of which each may have a number of tracks – with a nice, neat LINQ query:

var artists = _libraryRepository.FetchLibrary()
    .AsParallel()
    .GroupBy(track => track.Artist)
    .Select(group => new Artist(group.Key,
        group.GroupBy(track2 => track2.Album)
            .Select(group2 => new Album(group2.Key,group2)))
   );

And the models:

public class Artist
{
    public string Name { get; set; }
    public IEnumerable<Album> Albums { get; private set; }

    public Artist() { }

    public Artist(string name, IEnumerable<Album> albums)
    {
        Name = name;
        Albums = albums;
    }
}

public class Album
{
    public string Name { get; set; }
    public IEnumerable<Track> Tracks { get; private set; }

    public Album() { }

    public Album(string name, IEnumerabl<Track> tracks)
    {
        Name = name;
        Tracks = tracks;
    }
}

public class Track
{
    public Guid Id { get; private set;}
    public string Title { get; set; }
    public string Artist { get; set; }
    public string Album { get; set; }
    public string FilePathName { get; set; }
    public int? Year { get; set; }
    public int? TrackNumber { get; set; }

    public Track() {}

    public Track(Guid id, string filePathName)
    {
        Id = id;
        FilePathName = filePathName;
    }
}

Got comments?  Tweet me @padgettrowell

Advertisements