假設我們有一些電影的元數據:
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);
}
}
或者,組分類,而不是使用不同的(雖然我覺得在這種情況下清晰 - 更清晰 - 注意我最終不得不區分標題):
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);
}
}
(注意:這裏我提出了一個不同的方法。它可能不適用於你正在做的事情,但我覺得我需要更多的信息才能給出更好的答案。)
你能給我們一個更具體的例子嗎?我認爲你不需要*排序*;我想你想*分組*。但是沒有一個例子就很難說。 – 2012-04-12 19:57:18
最後的目的地是「分組」,是的。但是對於開發方面,pivotviewer需要用於屬性(StringProperty,NumericProperty,...)的數據字段必須具有Sort()方法。這導致我使用IComparable接口來實現SLCategory,然後是CompareTo方法。所以我的問題現在指向CompareTo方法。 – ducnh 2012-04-14 08:00:15