0

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ducnh
  • 260
  • 1
  • 3
  • 10
  • 4
    Can you give us a more concrete example? I don't think you want *sorting* at all; I think you want *grouping*. But it is hard to say without an example. – Eric Lippert Apr 12 '12 at 19:57
  • The final destination is "grouping", yes. But with development aspect, the pivotviewer requires data field used for property (StringProperty, NumericProperty, ...) must have a Sort() method. That leads me to implement SLCategory with IComparable interface, and then is CompareTo method. So my problem is now point to that CompareTo method. – ducnh Apr 14 '12 at 08:00

1 Answers1

1

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.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
payo
  • 4,501
  • 1
  • 24
  • 32