如何对具有多个变量的类的List进行多级排序

时间:2011-07-12 17:05:38

标签: c# list sorting c#-4.0

我有一个名为Movies的类,声明了以下变量:

string Title;
string Plot;
string MPAA;
string Certification;
string[] Genres;

我使用以下代码创建电影列表:

Movie m = new Movie(strTitle, strPlot, strMPAA, strCertification, strArrGenres);
MovieList.Add(m);

我现在正试图找出对列表进行排序的最佳方法。我需要做两种,第一种是简单的按标题排序。我试图使用LINQ,但我无法弄清楚如何正确访问Movie中的变量。

第二个会更棘手。我需要按类型排序。每部电影当然可以有多个类型,我知道我最终会有多部电影,因为这部电影将出现在每个类型中。

2 个答案:

答案 0 :(得分:8)

MovieList.OrderBy(m => m.Title)

MovieList.OrderBy(m => m.Genre).ThenBy(m => m.Title)

应该这样做。

如果您想要降序排序

,请使用.OrderByDescending().ThenByDescending()

答案 1 :(得分:2)

我不理解你是如何根据类型排序的,如果它们包含在电影中,也许你想按类型过滤然后按标题排序?

    class Movie
    {
        public string Title { get; set; }
        public string[] Genres { get; set; }
    }
    static void Main(string[] args)
    {
        var movies = new List<Movie>();
        movies.Add(new Movie { Title = "Pulp Fiction", Genres = new string[] { "Crime", "Thriller" } });
        movies.Add(new Movie { Title = "Back to the Future", Genres = new string[] { "Adventure", "Sci-Fi" } });
        movies.Add(new Movie { Title = "The Dark Knight", Genres = new string[] { "Action", "Crime" } });

        var byTitle = from m in movies orderby m.Title select m;

        var crimeMovies = from m in movies where m.Genres.Contains("Crime") orderby m.Title select m;
    }

编辑:选择带流派的电影并按流派排序,然后按标题排序(根据评论):

        var distinctGenres = from m in movies
                             from genre in m.Genres
                             group genre by genre into genres
                             select genres.First();                          

        var moviesWithGenre = from g in distinctGenres
                              from m in movies
                              where m.Genres.Contains(g)
                              orderby g, m.Title
                              select new { Genre = g, Movie = m };

        foreach (var m in moviesWithGenre)
        {
            Console.WriteLine("Genre: "+ m.Genre + " - " + m.Movie.Title);
        }

输出:

Genre: Action - The Dark Knight
Genre: Adventure - Back to the Future
Genre: Crime - Pulp Fiction
Genre: Crime - The Dark Knight
Genre: Sci-Fi - Back to the Future
Genre: Thriller - Pulp Fiction