C# - sorting a list inside of a struct
I have an assignment for school that I'm having trouble with. The assignment is to create a console app that allows users to add, modify and view a list of movies. Each movie contains attributes like a title, a year, a director, etc. I have to use the following structs:
struct Movie{
public string title;
public string year;
public string director;
public float quality;
public string mpaaRating;
public string genre;
public List<string> cast;
public List<string> quotes;
public List<string> keywords;
}
struct MovieList{
public int length;
public Movie[] movie;
}
...
MovieList List = new MovieList()
Here's the part I'm having trouble with. I need to sort List by the movie title开发者_如何学JAVA. I'm having trouble figuring out what the correct way to go about this is. Anyone have any advice?
First of all, those should not be structs, they should be classes. A structure is intended for a type that represents a single value, and is much more complicated to implement properly than a class.
You can sort the movies like this:
List.movie = List.movie.OrderBy(m => m.title).ToArray();
Since it is an array (addressed separately):
Array.Sort(List.movie,
(a,b)=>string.Compare(a.title,b.title));
You need to sort the array movie
. So just use any sorting method, such as Merge Sort
.
The decision if a movie is larger/smaller than another decide by comparing the titles.
movie[a].title.CompareTo(movie[b].title)
精彩评论