Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Sorting Array of objects

Sorting Array of objects

Scheduled Pinned Locked Moved C#
algorithmsdata-structureshelp
21 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • R Rizwan Rathore

    Hi All, I have made a class Words.....and m using an array of it.....and i want to sort this array according to its data member Term (it also has other data members). which is a string....wat is the easiest and effeiceint way of doing it plzz tell in detail looking forward for help Regards,

    L Offline
    L Offline
    Lost User
    wrote on last edited by
    #2

    See this article. You need to implement the IComparable interface and add a function CompareTo to your class. regards

    R 1 Reply Last reply
    0
    • L Lost User

      See this article. You need to implement the IComparable interface and add a function CompareTo to your class. regards

      R Offline
      R Offline
      Rizwan Rathore
      wrote on last edited by
      #3

      Hi Sir, Well the article u have suggested is quite complex coz i think it is about sorting objects of different classes.....i just need to sort object of a single class on the base of a specific data member........isnt there any easy way to do this :( Looking forward for help Regards,

      R 1 Reply Last reply
      0
      • R Rizwan Rathore

        Hi Sir, Well the article u have suggested is quite complex coz i think it is about sorting objects of different classes.....i just need to sort object of a single class on the base of a specific data member........isnt there any easy way to do this :( Looking forward for help Regards,

        R Offline
        R Offline
        Robert Rohde
        wrote on last edited by
        #4

        You should also have read his second sentence. Here a little example:

        public class MyClass : IComparable {
        private string _myValue;

        public int CompareTo(object o) {
        return _myValue.CompareTo(((MyClass)o)._myValue);
        }
        }

        R 1 Reply Last reply
        0
        • R Rizwan Rathore

          Hi All, I have made a class Words.....and m using an array of it.....and i want to sort this array according to its data member Term (it also has other data members). which is a string....wat is the easiest and effeiceint way of doing it plzz tell in detail looking forward for help Regards,

          B Offline
          B Offline
          BoneSoft
          wrote on last edited by
          #5

          using System;
          using System.Collections;

          namespace Test {
          // your class
          public class Word {
          private string value;
          private string anothervalue;

          	public string Value {
          		get { return value; }
          		set { value = value; }
          	}
          
          	public string AnotherValue {
          		get { return anothervalue; }
          		set { anothervalue = value; }
          	}
          }
          
          public class WordComparer : IComparer {
          	public int Compare(object x, object y) {
          		Word w1 = x as Word;
          		Word w2 = y as Word;
          		if (w1 == null || w2 == null) { return 0; }
          		return w1.Value.CompareTo(w2.Word);
          	}
          }
          
          // your application
          public class Application {
          	public Word\[\] Sort(Word\[\] words) {
          		return Array.Sort(words, new WordComparer());
          	}
          }
          

          }

          R 1 Reply Last reply
          0
          • R Robert Rohde

            You should also have read his second sentence. Here a little example:

            public class MyClass : IComparable {
            private string _myValue;

            public int CompareTo(object o) {
            return _myValue.CompareTo(((MyClass)o)._myValue);
            }
            }

            R Offline
            R Offline
            Rizwan Rathore
            wrote on last edited by
            #6

            how can i call this in my class? and wat is the purpose of this _myValue variable. looking forward for help Regards, -- modified at 11:59 Tuesday 23rd May, 2006

            R 1 Reply Last reply
            0
            • R Rizwan Rathore

              how can i call this in my class? and wat is the purpose of this _myValue variable. looking forward for help Regards, -- modified at 11:59 Tuesday 23rd May, 2006

              R Offline
              R Offline
              Robert Rohde
              wrote on last edited by
              #7

              Ok some more details :): MyClass is the class you want to get sorted. _myValue is the field or whatever by which you want to sort the data. Instead of using a field you could also use a property or something else. Now assuming you have filled instances of this class into an ArrayList you can sort it with:

              list.Sort();

              If you have an array (MyClass[] myArray) of your object than you can sort it with:

              Array.Sort(myArray);

              Internally the Sort methods will call CompareTo to determine the correct ordering.

              R 1 Reply Last reply
              0
              • B BoneSoft

                using System;
                using System.Collections;

                namespace Test {
                // your class
                public class Word {
                private string value;
                private string anothervalue;

                	public string Value {
                		get { return value; }
                		set { value = value; }
                	}
                
                	public string AnotherValue {
                		get { return anothervalue; }
                		set { anothervalue = value; }
                	}
                }
                
                public class WordComparer : IComparer {
                	public int Compare(object x, object y) {
                		Word w1 = x as Word;
                		Word w2 = y as Word;
                		if (w1 == null || w2 == null) { return 0; }
                		return w1.Value.CompareTo(w2.Word);
                	}
                }
                
                // your application
                public class Application {
                	public Word\[\] Sort(Word\[\] words) {
                		return Array.Sort(words, new WordComparer());
                	}
                }
                

                }

                R Offline
                R Offline
                Rizwan Rathore
                wrote on last edited by
                #8

                Hi Sir, when i am trying to do this in this way

                public class WordComparer : IComparer
                {

                public int Compare(object x, object y) 
                {			
                	Terminology w1 = x as Terminology;			
                	Terminology w2 = y as Terminology;			
                	if (w1 == null || w2 == null) { return 0; }		
                	return w1.term.CompareTo(w2.term);		
                }
                

                }

                public class TextMiner : System.Windows.Forms.Form
                {
                some code here........
                public Terminology[] word = new Terminology[WORDS];
                public void Indexer()
                {
                Array.Sort(word, new WordComparer());
                }
                }

                well it compiles fine but when i try to access the objects of that sorted class it gives null object reference exception

                for(int i = 0; i < Terminology.Count; i ++)
                {
                do something with word[i];
                }

                well this exception comes when the value of i is 0......and the program was working perfectly fine b4 that..... Looking forward for help Regards,

                B 1 Reply Last reply
                0
                • R Robert Rohde

                  Ok some more details :): MyClass is the class you want to get sorted. _myValue is the field or whatever by which you want to sort the data. Instead of using a field you could also use a property or something else. Now assuming you have filled instances of this class into an ArrayList you can sort it with:

                  list.Sort();

                  If you have an array (MyClass[] myArray) of your object than you can sort it with:

                  Array.Sort(myArray);

                  Internally the Sort methods will call CompareTo to determine the correct ordering.

                  R Offline
                  R Offline
                  Rizwan Rathore
                  wrote on last edited by
                  #9

                  Hi Sir, i am trying to do this in this way

                  public class TextMiner : System.Windows.Forms.Form , IComparable
                  {
                  public Terminology[] word = new Terminology[WORDS];
                  private string strValue = "term";
                  public int CompareTo(object obj)
                  {
                  Terminology w = (Terminology) obj;
                  return( strValue.CompareTo( w.term ));
                  }

                       public void Indexer()
                       {
                               Aray.Sort(word);
                       }
                  

                  }

                  it compiles without any error but it throws this exception during execution An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll Additional information: Specified IComparer threw an exception. tell me what i m doing wrong and how i can correct it.... looking forward for help Regards,

                  R 1 Reply Last reply
                  0
                  • R Rizwan Rathore

                    Hi Sir, when i am trying to do this in this way

                    public class WordComparer : IComparer
                    {

                    public int Compare(object x, object y) 
                    {			
                    	Terminology w1 = x as Terminology;			
                    	Terminology w2 = y as Terminology;			
                    	if (w1 == null || w2 == null) { return 0; }		
                    	return w1.term.CompareTo(w2.term);		
                    }
                    

                    }

                    public class TextMiner : System.Windows.Forms.Form
                    {
                    some code here........
                    public Terminology[] word = new Terminology[WORDS];
                    public void Indexer()
                    {
                    Array.Sort(word, new WordComparer());
                    }
                    }

                    well it compiles fine but when i try to access the objects of that sorted class it gives null object reference exception

                    for(int i = 0; i < Terminology.Count; i ++)
                    {
                    do something with word[i];
                    }

                    well this exception comes when the value of i is 0......and the program was working perfectly fine b4 that..... Looking forward for help Regards,

                    B Offline
                    B Offline
                    BoneSoft
                    wrote on last edited by
                    #10

                    I can't say much about the exception without seeing how you're setting up the arrays... But from your code snippet above, Array.Sort returns a new array. Try:

                    public class TextMiner : System.Windows.Forms.Form {
                    //some code here........
                    public Terminology[] word = new Terminology[WORDS];
                    public void Indexer() {
                    word = Array.Sort(word, new WordComparer());
                    }
                    }

                    Visit BoneSoft.com

                    R R 2 Replies Last reply
                    0
                    • B BoneSoft

                      I can't say much about the exception without seeing how you're setting up the arrays... But from your code snippet above, Array.Sort returns a new array. Try:

                      public class TextMiner : System.Windows.Forms.Form {
                      //some code here........
                      public Terminology[] word = new Terminology[WORDS];
                      public void Indexer() {
                      word = Array.Sort(word, new WordComparer());
                      }
                      }

                      Visit BoneSoft.com

                      R Offline
                      R Offline
                      Robert Rohde
                      wrote on last edited by
                      #11

                      BoneSoft wrote:

                      Array.Sort returns a new array

                      No it doesn't - it sorts the existing instance

                      B 1 Reply Last reply
                      0
                      • R Rizwan Rathore

                        Hi Sir, i am trying to do this in this way

                        public class TextMiner : System.Windows.Forms.Form , IComparable
                        {
                        public Terminology[] word = new Terminology[WORDS];
                        private string strValue = "term";
                        public int CompareTo(object obj)
                        {
                        Terminology w = (Terminology) obj;
                        return( strValue.CompareTo( w.term ));
                        }

                             public void Indexer()
                             {
                                     Aray.Sort(word);
                             }
                        

                        }

                        it compiles without any error but it throws this exception during execution An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll Additional information: Specified IComparer threw an exception. tell me what i m doing wrong and how i can correct it.... looking forward for help Regards,

                        R Offline
                        R Offline
                        Robert Rohde
                        wrote on last edited by
                        #12

                        As you sort a Terminology array also the Terminology class should implement IComparable and not the Form.

                        R 1 Reply Last reply
                        0
                        • B BoneSoft

                          I can't say much about the exception without seeing how you're setting up the arrays... But from your code snippet above, Array.Sort returns a new array. Try:

                          public class TextMiner : System.Windows.Forms.Form {
                          //some code here........
                          public Terminology[] word = new Terminology[WORDS];
                          public void Indexer() {
                          word = Array.Sort(word, new WordComparer());
                          }
                          }

                          Visit BoneSoft.com

                          R Offline
                          R Offline
                          Rizwan Rathore
                          wrote on last edited by
                          #13

                          BoneSoft wrote:

                          word = Array.Sort(word, new WordComparer());

                          well i ve tried this already but it gives compile time error that cant covert type void to type TextMiner.Terminology[] :(

                          1 Reply Last reply
                          0
                          • R Robert Rohde

                            As you sort a Terminology array also the Terminology class should implement IComparable and not the Form.

                            R Offline
                            R Offline
                            Rizwan Rathore
                            wrote on last edited by
                            #14

                            sir it also didnt work :( i ve written the same code in the CompareTo function which i ve written in TextMiner class but it made no difference again same exception :( is there any way out of this ?? looking forward for help Regards,

                            R 1 Reply Last reply
                            0
                            • R Rizwan Rathore

                              sir it also didnt work :( i ve written the same code in the CompareTo function which i ve written in TextMiner class but it made no difference again same exception :( is there any way out of this ?? looking forward for help Regards,

                              R Offline
                              R Offline
                              Robert Rohde
                              wrote on last edited by
                              #15

                              I assume some error is thrown within your CompareTo method. You should probably check if the are null values within your array or probably if sometimes term is null.

                              R 1 Reply Last reply
                              0
                              • R Robert Rohde

                                I assume some error is thrown within your CompareTo method. You should probably check if the are null values within your array or probably if sometimes term is null.

                                R Offline
                                R Offline
                                Rizwan Rathore
                                wrote on last edited by
                                #16

                                well the exception doesnt come during sorting it comes after the sorting the statement i m cofused about is the use of private string strValue = "term"; isnt there any error in this statement?? i mean term is the variable of terminology class and i m declaring it as a string value in TextMiner class how will this work??

                                R 1 Reply Last reply
                                0
                                • R Rizwan Rathore

                                  well the exception doesnt come during sorting it comes after the sorting the statement i m cofused about is the use of private string strValue = "term"; isnt there any error in this statement?? i mean term is the variable of terminology class and i m declaring it as a string value in TextMiner class how will this work??

                                  R Offline
                                  R Offline
                                  Robert Rohde
                                  wrote on last edited by
                                  #17

                                  Could you please post the important part of the Terminology class and the Sort call you are currently doing? Maybe I can help you then.

                                  R 1 Reply Last reply
                                  0
                                  • R Robert Rohde

                                    Could you please post the important part of the Terminology class and the Sort call you are currently doing? Maybe I can help you then.

                                    R Offline
                                    R Offline
                                    Rizwan Rathore
                                    wrote on last edited by
                                    #18

                                    public class Terminology : IComparable
                                    {
                                    private string term;
                                    private int df;
                                    private int qTf;
                                    private double qWeight;
                                    private ArrayList tf = new ArrayList();
                                    private ArrayList position= new ArrayList();
                                    private ArrayList docID= new ArrayList();
                                    private static int Count;

                                        public int CompareTo(object obj)
                                    {
                                    	Terminology w = (Terminology) obj;
                                    	return( w.term.CompareTo( w.term ));
                                    }
                                    

                                    //only method in this class other than properties and constructors
                                    public void incDF()
                                    {
                                    df++;
                                    }
                                    }

                                    now moving to TextMiner class

                                    public class TextMiner : System.Windows.Forms.Form , IComparable
                                    {
                                    const int WORDS = 20000;
                                    public Terminology[] word = new Terminology[WORDS];
                                    public void Indexer()
                                    {
                                    Array.Sort(word);
                                    }
                                    private string strValue = "term";
                                    public int CompareTo(object obj)
                                    {
                                    Terminology w = (Terminology) obj;
                                    return( strValue.CompareTo( w.term ));
                                    }
                                    }

                                    it gives this exception An unhandled exception of type 'System.NullReferenceException' occurred in 2ndAssignment.exe Additional information: Object reference not set to an instance of an object. and on this statement

                                    for(int j = 0; j < Terminology.count-1; j++)
                                    {
                                    sw.Write(j+1 +"\t"+word[j].term.PadRight(20,' '));
                                    }

                                    and the exceptions comes when the value of j is 0....m really confused :( looking forward for help Regards, -- modified at 5:43 Wednesday 24th May, 2006

                                    R 1 Reply Last reply
                                    0
                                    • R Rizwan Rathore

                                      public class Terminology : IComparable
                                      {
                                      private string term;
                                      private int df;
                                      private int qTf;
                                      private double qWeight;
                                      private ArrayList tf = new ArrayList();
                                      private ArrayList position= new ArrayList();
                                      private ArrayList docID= new ArrayList();
                                      private static int Count;

                                          public int CompareTo(object obj)
                                      {
                                      	Terminology w = (Terminology) obj;
                                      	return( w.term.CompareTo( w.term ));
                                      }
                                      

                                      //only method in this class other than properties and constructors
                                      public void incDF()
                                      {
                                      df++;
                                      }
                                      }

                                      now moving to TextMiner class

                                      public class TextMiner : System.Windows.Forms.Form , IComparable
                                      {
                                      const int WORDS = 20000;
                                      public Terminology[] word = new Terminology[WORDS];
                                      public void Indexer()
                                      {
                                      Array.Sort(word);
                                      }
                                      private string strValue = "term";
                                      public int CompareTo(object obj)
                                      {
                                      Terminology w = (Terminology) obj;
                                      return( strValue.CompareTo( w.term ));
                                      }
                                      }

                                      it gives this exception An unhandled exception of type 'System.NullReferenceException' occurred in 2ndAssignment.exe Additional information: Object reference not set to an instance of an object. and on this statement

                                      for(int j = 0; j < Terminology.count-1; j++)
                                      {
                                      sw.Write(j+1 +"\t"+word[j].term.PadRight(20,' '));
                                      }

                                      and the exceptions comes when the value of j is 0....m really confused :( looking forward for help Regards, -- modified at 5:43 Wednesday 24th May, 2006

                                      R Offline
                                      R Offline
                                      Robert Rohde
                                      wrote on last edited by
                                      #19

                                      Several things: 1. In the first snippet the CompareTo should look like the following:

                                      public int CompareTo(object obj)
                                      {
                                      Terminology w = (Terminology) obj;
                                      return( this.term.CompareTo( w.term ));
                                      }

                                      In your implementation you compared w.term with itself. 2. The following part isn't needed (as far as I can see from your snippets):

                                      private string strValue = "term";
                                      public int CompareTo(object obj)
                                      {
                                      Terminology w = (Terminology) obj;
                                      return( strValue.CompareTo( w.term ));
                                      }
                                      }

                                      3. If you are getting such an error when j is 0 than my previous assumption that there are null values in your array seems right. The first element of the word array seems to be null. You could verify this for example with the following code:

                                      for(int j = 0; j < Terminology.count-1; j++)
                                      {
                                      if (word[j] == null)
                                      MessageBox.Show("word array at index " + j + " is null");
                                      else if (word[j].term == null)
                                      MessageBox.Show("term property in word array at index " + j + " is null");
                                      sw.Write(j+1 +"\t"+word[j].term.PadRight(20,' '));
                                      }

                                      R 1 Reply Last reply
                                      0
                                      • R Robert Rohde

                                        Several things: 1. In the first snippet the CompareTo should look like the following:

                                        public int CompareTo(object obj)
                                        {
                                        Terminology w = (Terminology) obj;
                                        return( this.term.CompareTo( w.term ));
                                        }

                                        In your implementation you compared w.term with itself. 2. The following part isn't needed (as far as I can see from your snippets):

                                        private string strValue = "term";
                                        public int CompareTo(object obj)
                                        {
                                        Terminology w = (Terminology) obj;
                                        return( strValue.CompareTo( w.term ));
                                        }
                                        }

                                        3. If you are getting such an error when j is 0 than my previous assumption that there are null values in your array seems right. The first element of the word array seems to be null. You could verify this for example with the following code:

                                        for(int j = 0; j < Terminology.count-1; j++)
                                        {
                                        if (word[j] == null)
                                        MessageBox.Show("word array at index " + j + " is null");
                                        else if (word[j].term == null)
                                        MessageBox.Show("term property in word array at index " + j + " is null");
                                        sw.Write(j+1 +"\t"+word[j].term.PadRight(20,' '));
                                        }

                                        R Offline
                                        R Offline
                                        Rizwan Rathore
                                        wrote on last edited by
                                        #20

                                        Robert Rohde wrote:

                                        if (word[j] == null) MessageBox.Show("word array at index " + j + " is null");

                                        Sir it is showing entire array of word as null.....but it works perfectly fine without sorting..........how can all the values changed to null??

                                        1 Reply Last reply
                                        0
                                        • R Robert Rohde

                                          BoneSoft wrote:

                                          Array.Sort returns a new array

                                          No it doesn't - it sorts the existing instance

                                          B Offline
                                          B Offline
                                          BoneSoft
                                          wrote on last edited by
                                          #21

                                          Yeah, don't know what I was thinking... Visit BoneSoft.com

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups