Search code examples
c#silverlight-5.0icomparablepivotviewer

What sorting strategy should I use for this case?


I have a list of strings that presents name of categories that a film belongs to. I make a class define that list, implement List<String> and IComparable interface, in order to use in PivotViewerStringProperty as below:

public class SLCategoryList : List<String>, IComparable
{
    public int CompareTo(object obj)
    {
        return this[0].CompareTo((obj as SLCategoryList)[0]);
    }
}

The point here is a film should belong to many categories, and I want a sorting strategy so it can make pivotviewer and sort a database of films by each category. Therefore, it should show the same film at two or more categories at once when the application is running.

What sorting strategy should I use?


Solution

  • Let's assume we have some movie meta data:

    class MovieMetaData
    {
        public string Title { get; set; }
        public List<string> Categories { get; set; }
    }
    
    IEnumerable<MovieMetaData> movies = /* Some initialization. */;
    

    I would group my movies in one of two (very similar) ways:

    var categories = movies.SelectMany(m => m.Categories).Distinct();
    var groups = categories
        .Select(c => Tuple.Create(c, movies
                .Where(m => m.Categories.Contains(c))
                .OrderBy(m => m.Title)));
    
    
    foreach (var category in groups)
    {
        Console.WriteLine("Category: {0}", category.Item1);
    
        foreach (var movie in category.Item2)
        {
            Console.WriteLine(movie.Title);
        }
    }
    

    Or, group the categories rather than using distinct (though I feel distinct in this case is cleaner - note I end up having to distinct the titles anyway):

    var categories = movies.SelectMany(m => m.Categories);
    var groups = categories
        .Select(c => Tuple.Create(c, movies
                .Where(m => m.Categories.Contains(c))
                .OrderBy(m => m.Title)))
        .GroupBy(g => g.Item1);
    
    
    foreach (var category in groups)
    {
        Console.WriteLine("Category: {0}", category.Key);
    
        foreach (var movie in category.SelectMany(c => c.Item2).Select(m => m.Title).Distinct())
        {
            Console.WriteLine(movie);
        }
    }
    

    (Note: here I have suggested a different approach. It may not work with what you are trying to do, but I feel I would need more information to give a better answer.)