0

I want to sort anarray by the object type. So all songs are together, all book are together, and all movies are together.

I am reading a file and determine what each object should be. then creating the object and adding it to the array.

EDIT: Here is the actual code.

static Media[] ReadData()
{
 List<Media> things = new List<Media>();
 try
 {
  String filePath = "resources/Data.txt";
  string Line;
  int counter = 0; // used to check if you have reached the max 
  number of allowed objects (100)
  using (StreamReader File = new System.IO.StreamReader(filePath))
  {
   while ((Line = File.ReadLine()) != null)
   {

This is where each object is created. The file search for a key word in the beginning of the line, then creates the corresponding object. It will split the information on the first line of the object and will read each line until a "-" character is found and pass each line into the summary. The summary is then decrypted and the created object is passed into an array List. Finally if the array list reaches 100, it will print "You have reach max number of objects" and stop reading the file.

    if (Line.StartsWith("BOOK"))
    {
     String[] tempArray = Line.Split('|'); 
     //foreach (string x in tempArray){Console.WriteLine(x);} //This is used 
for testing 
     Book tempBook = new Book(tempArray[1], 
     int.Parse(tempArray[2]), tempArray[3]);
     while ((Line = File.ReadLine()) != null)
     {
      if (Line.StartsWith("-")){break;}
      tempBook.Summary = tempBook.Summary + Line;
     }
     tempBook.Summary = tempBook.Decrypt();
     things.Add(tempBook);
     counter++;
    }
    else if (Line.StartsWith("SONG"))
    {
     String[] tempArray = Line.Split('|');
     //foreach (string x in tempArray) 
     {Console.WriteLine(x);} //This is used for testing 
     Song tempSong = new Song(tempArray[1], 
     int.Parse(tempArray[2]), tempArray[3], tempArray[4]);
     things.Add(tempSong);
     counter++;
    }
    else if (Line.StartsWith("MOVIE"))
    {
     String[] tempArray = Line.Split('|');
     //foreach (string x in tempArray) 
     {Console.WriteLine(x);} //This is used for testing 
     Movie tempMovie = new Movie(tempArray[1], 
     int.Parse(tempArray[2]), tempArray[3]);
     while ((Line = File.ReadLine()) != null)
     {
      if (Line.StartsWith("-")) { break; }
      tempMovie.Summary = tempMovie.Summary + Line;
     }
     tempMovie.Summary = tempMovie.Decrypt();
     things.Add(tempMovie);
     counter++;
    }
    if (counter == 100)
    {
     Console.WriteLine("You have reached the maximum number of media 
objects.");
     break;
    }
   }
  File.Close();
 }
}
return things.ToArray(); // Convert array list to an Array and return the 
array.
}

In the main code, I have this:

Media[] mediaObjects = new Media[100];
Media[] temp = ReadData();
int input; // holds the input from a user to determin which action to take
for (int i = 0; i<temp.Length;i++){ mediaObjects[i] = temp[i]; }

I want the array of mediaObjects to be sorted by the what type of objects.

I have also used Icomparable to do an arrayList.sort() but still no luck.

public int CompareTo(object obj)
    {
        if (obj == null)
        {
            return 1;
        }
        Song temp = obj as Song;
        if (temp != null)
        {
            //Type is a string
            return this.Type.CompareTo(temp.Type);
        }
        else
        {
            return 1;
        }
    }
6
  • Show us your code. Anything you tried? This is not a write-my-code site. Commented Dec 22, 2017 at 18:38
  • Ive tried a few things but I feel like I dont know where I should start. Commented Dec 22, 2017 at 18:57
  • I have tried this mediaObjects.OrderByDescending(Media, mediaObjects.GetType()); Commented Dec 22, 2017 at 18:57
  • 1
    well, in order to be able to sort, you need to be able to compare objects, thus a way to determine whether object1 > object2 or object1 == object2. That usually is implemented such that the values "inside" are compared, provided the objects are of the same type. If they're of different type, you'll have to implement your own comparison operator. Commented Dec 22, 2017 at 22:09
  • 2
    mediaObjects.OrderByDescending(x => x.GetType().ToString()); Commented Dec 22, 2017 at 23:36

2 Answers 2

1

So I see you have BOOK, SONG and MOVIE types.

This is a classic case of implementing the IComparable interface - although you are correct with the interface name to implement, you are not using this correctly.

  1. Create a base class by the name MediaObject - this will be the main one for your other types of objects you create.
  2. Add the correct properties you need. In this case, the media type is the one in need.
  3. Let this class implement IComparable to help you with the comparison.
  4. override the CompareTo() method in the PROPER way
public class MediaObject : IComparable
{
  private string mediaType;
  public string MediaType
  {
     get  {return mediaType;}
     set {mediaType=value;}
  }
  public MediaObject(string mType)
  {
     MediaType = mType;
  }
  int IComparable.CompareTo(object obj)
  {
     MediaObject mo = (MediaObject)obj;
     return String.Compare(this.MediaType,mo.MediaType); //implement a case insensitive comparison if needed (for your research)
  }
}
  1. You can now compare the MediaObject objects In your main method directly.
Sign up to request clarification or add additional context in comments.

1 Comment

This was the idea I had in mind but this program was for a class assignment and we where not allowed to edit the code of the Media Object class, only the Movie, Song, and Book classes. That made things a lot harder. This does work though
0

Thank for the advice. I ended up just reformating how I was creating the list while reading it. I made multiple lists for each object then just happened each one on to the master list so It showed up sorted. I wish I figured that out before I made this long post.

As far as I could find, you can't sort by the type of object in a generic array. If anyone has a better solution feel free to post it.

1 Comment

I was just going through extension methods. What if you created an extension method for each object type to compare their type names which are strings? learn.microsoft.com/en-us/dotnet/csharp/programming-guide/…

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.