假设我们有一些电影元数据:
class MovieMetaData
{
public string Title { get; set; }
public List<string> Categories { get; set; }
}
IEnumerable<MovieMetaData> movies = /* Some initialization. */;
我会以两种(非常相似的)方式之一对我的电影进行分组:
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);
}
}
或者,对类别进行分组而不是使用 distinct(尽管在这种情况下我觉得不同更清晰 - 注意我最终不得不区分标题):
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);
}
}
(注意:在这里我提出了一种不同的方法。它可能不适用于您尝试做的事情,但我觉得我需要更多信息才能给出更好的答案。)