2

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. I'm having trouble figuring out what the correct way to go about this is. Anyone have any advice?

16
  • 1
    Firstly, neither of those types should be structs. Second; since you know about List-of-T, why use an array in MovieList - in fact, why have MovieList at all? Commented Dec 4, 2010 at 23:07
  • 1
    @fearofawhackplanet C doesn't have generics or access levels, so it's probably not C. and C# does have structs. Commented Dec 4, 2010 at 23:11
  • 1
    comment fail then :) weird i've been programming C# for two years and never seen struct used. guess i need to read more SO :) Commented Dec 4, 2010 at 23:18
  • 1
    @fearof - the good news is: that probably means you are using them correctly! it is very uncommon to write a struct in C# Commented Dec 4, 2010 at 23:20
  • 2
    seems a bit harsh that this question is being downvoted. it's not the OPs fault if his tutor gives him crap assignments. Commented Dec 4, 2010 at 23:20

3 Answers 3

2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

It should be noted that this creates a second array that is the ordered items (leaving the old array unchanged) - and then swaps the arrays.
2

Since it is an array (addressed separately):

Array.Sort(List.movie,
   (a,b)=>string.Compare(a.title,b.title));

Comments

0

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)

1 Comment

It is generally safer to use string.Compare(x,y), in case the first operand is null

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.