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
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. Need Help with SortedList<tkey,tvalue> [modified]

Need Help with SortedList<tkey,tvalue> [modified]

Scheduled Pinned Locked Moved C#
helpdatabasealgorithmsquestion
9 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.
  • G Offline
    G Offline
    gamer1127
    wrote on last edited by
    #1

    Hi. I'm now using the SortedList to sort the strings from the text file. Is it possible to have a single key as the basis for comparing each string? If yes, I want to know how i will prevent the key from duplicating. Can someone help me? As of now this is what I accomplished:

    public static void SortByLastName(ref string[] arrayOfLastNames, ref string[] arrayOfFirstNames, ref string[] arrayOfPlateNum, ref string[] arrayOfType, ref string[] arrayOfYear)
    {
    Console.Clear();

            int vehicleCountInt = 0;
    
            Console.WriteLine("SHOW DATABASE: SORTING BY LAST NAME\\n");
    
            using (StreamReader countVehicle = new StreamReader("vehiclecount.txt"))
            {
                vehicleCountInt = Int32.Parse(countVehicle.ReadLine());
    
                countVehicle.Close();
            }
    
            SortedList sortedLastName = new SortedList(vehicleCountInt);
            
            using (StreamReader outputLastNames = new StreamReader("lastnames.txt"))
            {
                
                for (int i = 0; i < vehicleCountInt; i++)
                {
                    arrayOfLastNames\[i\] = outputLastNames.ReadLine();
    
                    string keyVal = arrayOfLastNames\[i\];
    
                    sortedLastName.Add(keyVal, arrayOfLastNames\[i\]); //I'm having a run-time error here that throws the ArgumentException
    
                    if (!sortedLastName.ContainsKey(keyVal))
                    {
                        sortedLastName.Add(keyVal, arrayOfLastNames\[i\]);
                    }
                    else
                    {
                        sortedLastName.Remove(keyVal);
                        sortedLastName.Add(keyVal, arrayOfLastNames\[i\]);
                    }
    
                    Console.WriteLine("{0}", sortedLastName.Keys\[i\]);//And sometimes throws the exception ArgumentOutOfRange Exception
                }
                
                
                outputLastNames.Close();
            }
    
        }
    

    modified on Friday, September 4, 2009 11:47 AM

    L G L 3 Replies Last reply
    0
    • G gamer1127

      Hi. I'm now using the SortedList to sort the strings from the text file. Is it possible to have a single key as the basis for comparing each string? If yes, I want to know how i will prevent the key from duplicating. Can someone help me? As of now this is what I accomplished:

      public static void SortByLastName(ref string[] arrayOfLastNames, ref string[] arrayOfFirstNames, ref string[] arrayOfPlateNum, ref string[] arrayOfType, ref string[] arrayOfYear)
      {
      Console.Clear();

              int vehicleCountInt = 0;
      
              Console.WriteLine("SHOW DATABASE: SORTING BY LAST NAME\\n");
      
              using (StreamReader countVehicle = new StreamReader("vehiclecount.txt"))
              {
                  vehicleCountInt = Int32.Parse(countVehicle.ReadLine());
      
                  countVehicle.Close();
              }
      
              SortedList sortedLastName = new SortedList(vehicleCountInt);
              
              using (StreamReader outputLastNames = new StreamReader("lastnames.txt"))
              {
                  
                  for (int i = 0; i < vehicleCountInt; i++)
                  {
                      arrayOfLastNames\[i\] = outputLastNames.ReadLine();
      
                      string keyVal = arrayOfLastNames\[i\];
      
                      sortedLastName.Add(keyVal, arrayOfLastNames\[i\]); //I'm having a run-time error here that throws the ArgumentException
      
                      if (!sortedLastName.ContainsKey(keyVal))
                      {
                          sortedLastName.Add(keyVal, arrayOfLastNames\[i\]);
                      }
                      else
                      {
                          sortedLastName.Remove(keyVal);
                          sortedLastName.Add(keyVal, arrayOfLastNames\[i\]);
                      }
      
                      Console.WriteLine("{0}", sortedLastName.Keys\[i\]);//And sometimes throws the exception ArgumentOutOfRange Exception
                  }
                  
                  
                  outputLastNames.Close();
              }
      
          }
      

      modified on Friday, September 4, 2009 11:47 AM

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

      gamer1127 wrote:

      sortedLastName.Add(keyVal, arrayOfLastNames[i]); //I'm having a run-time error here that throws the ArgumentException

      What information does the debugger show? The ArgumenException implies that one of the arguments to the sortedLastName.Add() call contains an invalid value, quite possibly null.

      G 1 Reply Last reply
      0
      • L Lost User

        gamer1127 wrote:

        sortedLastName.Add(keyVal, arrayOfLastNames[i]); //I'm having a run-time error here that throws the ArgumentException

        What information does the debugger show? The ArgumenException implies that one of the arguments to the sortedLastName.Add() call contains an invalid value, quite possibly null.

        G Offline
        G Offline
        gamer1127
        wrote on last edited by
        #3

        It says that an entry with the same key already exists.

        1 Reply Last reply
        0
        • G gamer1127

          Hi. I'm now using the SortedList to sort the strings from the text file. Is it possible to have a single key as the basis for comparing each string? If yes, I want to know how i will prevent the key from duplicating. Can someone help me? As of now this is what I accomplished:

          public static void SortByLastName(ref string[] arrayOfLastNames, ref string[] arrayOfFirstNames, ref string[] arrayOfPlateNum, ref string[] arrayOfType, ref string[] arrayOfYear)
          {
          Console.Clear();

                  int vehicleCountInt = 0;
          
                  Console.WriteLine("SHOW DATABASE: SORTING BY LAST NAME\\n");
          
                  using (StreamReader countVehicle = new StreamReader("vehiclecount.txt"))
                  {
                      vehicleCountInt = Int32.Parse(countVehicle.ReadLine());
          
                      countVehicle.Close();
                  }
          
                  SortedList sortedLastName = new SortedList(vehicleCountInt);
                  
                  using (StreamReader outputLastNames = new StreamReader("lastnames.txt"))
                  {
                      
                      for (int i = 0; i < vehicleCountInt; i++)
                      {
                          arrayOfLastNames\[i\] = outputLastNames.ReadLine();
          
                          string keyVal = arrayOfLastNames\[i\];
          
                          sortedLastName.Add(keyVal, arrayOfLastNames\[i\]); //I'm having a run-time error here that throws the ArgumentException
          
                          if (!sortedLastName.ContainsKey(keyVal))
                          {
                              sortedLastName.Add(keyVal, arrayOfLastNames\[i\]);
                          }
                          else
                          {
                              sortedLastName.Remove(keyVal);
                              sortedLastName.Add(keyVal, arrayOfLastNames\[i\]);
                          }
          
                          Console.WriteLine("{0}", sortedLastName.Keys\[i\]);//And sometimes throws the exception ArgumentOutOfRange Exception
                      }
                      
                      
                      outputLastNames.Close();
                  }
          
              }
          

          modified on Friday, September 4, 2009 11:47 AM

          G Offline
          G Offline
          Gideon Engelberth
          wrote on last edited by
          #4

          gamer1127 wrote:

          sortedLastName.Add(keyVal, arrayOfLastNames[i]); //I'm having a run-time error here that throws the ArgumentException if (!sortedLastName.ContainsKey(keyVal)) { sortedLastName.Add(keyVal, arrayOfLastNames[i]); } else { sortedLastName.Remove(keyVal); sortedLastName.Add(keyVal, arrayOfLastNames[i]); }

          You did it wrong, then you did it right. Why do you even have the line that is getting the error? You are doing the same thing with the next if block.

          gamer1127 wrote:

          Console.WriteLine("{0}", sortedLastName.Keys[i]);//And sometimes throws the exception ArgumentOutOfRange Exception

          You are getting this error for the same reason you were getting the previous error. If you have a duplicate key, you will not have "i" items in the list. You need to check if that many keys exist before trying to write them out. On an style note, it appears that you have several properties of items all stored in separate arrays, and a single array of a class (with FirstName, LastName, PlateNumber, Type, and Year properties) may be better. Also, there is no reason to pass the array by ref just to change the values in them. If you are passing the array by ref so you can change the length, I would suggest returning an array instead, since you do not seem to be using the data already in the arrays.

          G 2 Replies Last reply
          0
          • G Gideon Engelberth

            gamer1127 wrote:

            sortedLastName.Add(keyVal, arrayOfLastNames[i]); //I'm having a run-time error here that throws the ArgumentException if (!sortedLastName.ContainsKey(keyVal)) { sortedLastName.Add(keyVal, arrayOfLastNames[i]); } else { sortedLastName.Remove(keyVal); sortedLastName.Add(keyVal, arrayOfLastNames[i]); }

            You did it wrong, then you did it right. Why do you even have the line that is getting the error? You are doing the same thing with the next if block.

            gamer1127 wrote:

            Console.WriteLine("{0}", sortedLastName.Keys[i]);//And sometimes throws the exception ArgumentOutOfRange Exception

            You are getting this error for the same reason you were getting the previous error. If you have a duplicate key, you will not have "i" items in the list. You need to check if that many keys exist before trying to write them out. On an style note, it appears that you have several properties of items all stored in separate arrays, and a single array of a class (with FirstName, LastName, PlateNumber, Type, and Year properties) may be better. Also, there is no reason to pass the array by ref just to change the values in them. If you are passing the array by ref so you can change the length, I would suggest returning an array instead, since you do not seem to be using the data already in the arrays.

            G Offline
            G Offline
            gamer1127
            wrote on last edited by
            #5

            Gideon Engelberth wrote:

            On an style note, it appears that you have several properties of items all stored in separate arrays, and a single array of a class (with FirstName, LastName, PlateNumber, Type, and Year properties) may be better.

            Can you please show an example for that? By the way, I already solved the problems. I'll get back to you guys when a new problem comes up. :laugh:

            1 Reply Last reply
            0
            • G Gideon Engelberth

              gamer1127 wrote:

              sortedLastName.Add(keyVal, arrayOfLastNames[i]); //I'm having a run-time error here that throws the ArgumentException if (!sortedLastName.ContainsKey(keyVal)) { sortedLastName.Add(keyVal, arrayOfLastNames[i]); } else { sortedLastName.Remove(keyVal); sortedLastName.Add(keyVal, arrayOfLastNames[i]); }

              You did it wrong, then you did it right. Why do you even have the line that is getting the error? You are doing the same thing with the next if block.

              gamer1127 wrote:

              Console.WriteLine("{0}", sortedLastName.Keys[i]);//And sometimes throws the exception ArgumentOutOfRange Exception

              You are getting this error for the same reason you were getting the previous error. If you have a duplicate key, you will not have "i" items in the list. You need to check if that many keys exist before trying to write them out. On an style note, it appears that you have several properties of items all stored in separate arrays, and a single array of a class (with FirstName, LastName, PlateNumber, Type, and Year properties) may be better. Also, there is no reason to pass the array by ref just to change the values in them. If you are passing the array by ref so you can change the length, I would suggest returning an array instead, since you do not seem to be using the data already in the arrays.

              G Offline
              G Offline
              gamer1127
              wrote on last edited by
              #6

              What if there are values that are the same? How will I show those two? I know that they must have different keys but how will I exactly do that? For example:

              Hibaler
              Balde
              Metin
              Dela Vega
              Dimagiba
              Pederoso
              Dinulos
              Du
              Gotengco
              Lira
              Guban
              Garraez
              Carpena
              Reyes //first value
              Zulueta
              Gonzalez
              Isidoro
              Marfa
              Reyes //second value
              Guinhawa
              Aaron
              Lazaro
              Obsum
              Molino
              Estenor
              Nolasco
              Paral
              Porillo
              Novillos
              Alihan

              How will I assign different values for the other so i can show them both after sorting?

              1 Reply Last reply
              0
              • G gamer1127

                Hi. I'm now using the SortedList to sort the strings from the text file. Is it possible to have a single key as the basis for comparing each string? If yes, I want to know how i will prevent the key from duplicating. Can someone help me? As of now this is what I accomplished:

                public static void SortByLastName(ref string[] arrayOfLastNames, ref string[] arrayOfFirstNames, ref string[] arrayOfPlateNum, ref string[] arrayOfType, ref string[] arrayOfYear)
                {
                Console.Clear();

                        int vehicleCountInt = 0;
                
                        Console.WriteLine("SHOW DATABASE: SORTING BY LAST NAME\\n");
                
                        using (StreamReader countVehicle = new StreamReader("vehiclecount.txt"))
                        {
                            vehicleCountInt = Int32.Parse(countVehicle.ReadLine());
                
                            countVehicle.Close();
                        }
                
                        SortedList sortedLastName = new SortedList(vehicleCountInt);
                        
                        using (StreamReader outputLastNames = new StreamReader("lastnames.txt"))
                        {
                            
                            for (int i = 0; i < vehicleCountInt; i++)
                            {
                                arrayOfLastNames\[i\] = outputLastNames.ReadLine();
                
                                string keyVal = arrayOfLastNames\[i\];
                
                                sortedLastName.Add(keyVal, arrayOfLastNames\[i\]); //I'm having a run-time error here that throws the ArgumentException
                
                                if (!sortedLastName.ContainsKey(keyVal))
                                {
                                    sortedLastName.Add(keyVal, arrayOfLastNames\[i\]);
                                }
                                else
                                {
                                    sortedLastName.Remove(keyVal);
                                    sortedLastName.Add(keyVal, arrayOfLastNames\[i\]);
                                }
                
                                Console.WriteLine("{0}", sortedLastName.Keys\[i\]);//And sometimes throws the exception ArgumentOutOfRange Exception
                            }
                            
                            
                            outputLastNames.Close();
                        }
                
                    }
                

                modified on Friday, September 4, 2009 11:47 AM

                L Offline
                L Offline
                Luc Pattyn
                wrote on last edited by
                #7

                why are you making everything much more complex than necessary? dictionaries (SortedList is a dictionary) require keys to be unique, which does not match your application; so forget about dictionaries as your primary storage. you can keep a list of strings (any strings including duplicates) in a List<string> which you can simply sort by calling myList.Sort() you can also define your own little class "MyType" (holding name, age, address, vehicleColor, whatever) and collect those in a List<MyType> Strings get sorted alphabetically by default; your own objects don't have a default sort order. If you need a (special) sort order (i.e. non-alphabetic for strings) you can easily do that with an object that implements IComparable; I wrote a little article[^] that explains it all. FWIW: I strongly recommend you buy and study a book on C# to increase your basic knowledge of the language and the .NET framework. Here[^] is why. :)

                Luc Pattyn

                :badger: :jig: :badger:

                Have a look at my entry for the lean-and-mean competition; please provide comments, feedback, discussion, and don’t forget to vote for it! Thank you.

                :jig: :badger: :jig:

                G 1 Reply Last reply
                0
                • L Luc Pattyn

                  why are you making everything much more complex than necessary? dictionaries (SortedList is a dictionary) require keys to be unique, which does not match your application; so forget about dictionaries as your primary storage. you can keep a list of strings (any strings including duplicates) in a List<string> which you can simply sort by calling myList.Sort() you can also define your own little class "MyType" (holding name, age, address, vehicleColor, whatever) and collect those in a List<MyType> Strings get sorted alphabetically by default; your own objects don't have a default sort order. If you need a (special) sort order (i.e. non-alphabetic for strings) you can easily do that with an object that implements IComparable; I wrote a little article[^] that explains it all. FWIW: I strongly recommend you buy and study a book on C# to increase your basic knowledge of the language and the .NET framework. Here[^] is why. :)

                  Luc Pattyn

                  :badger: :jig: :badger:

                  Have a look at my entry for the lean-and-mean competition; please provide comments, feedback, discussion, and don’t forget to vote for it! Thank you.

                  :jig: :badger: :jig:

                  G Offline
                  G Offline
                  gamer1127
                  wrote on last edited by
                  #8

                  Luc Pattyn wrote:

                  why are you making everything much more complex than necessary?

                  My answer to that is because the program that i'm creating is for the subject that i have about data structures. I can't use Array.Sort() etc because the solution that we presented is to use radix sort(which i didn't continue because I can't resolve the error i always get). We have a different subject for the fundamentals and other things about C#. But I'll take your advice. I already visited the links that you posted and read it especially about learning a new language. I already have a book, the title: C# Programming: From Program Analysis to Program Design by Barbara Doyle. But probably I'll do what you said there so I can have more knowledge about the language. :-D

                  L 1 Reply Last reply
                  0
                  • G gamer1127

                    Luc Pattyn wrote:

                    why are you making everything much more complex than necessary?

                    My answer to that is because the program that i'm creating is for the subject that i have about data structures. I can't use Array.Sort() etc because the solution that we presented is to use radix sort(which i didn't continue because I can't resolve the error i always get). We have a different subject for the fundamentals and other things about C#. But I'll take your advice. I already visited the links that you posted and read it especially about learning a new language. I already have a book, the title: C# Programming: From Program Analysis to Program Design by Barbara Doyle. But probably I'll do what you said there so I can have more knowledge about the language. :-D

                    L Offline
                    L Offline
                    Luc Pattyn
                    wrote on last edited by
                    #9

                    OK Now SortedList is not dealing with duplicate keys and not doing Radix Sort, so it is a bad choice. What you need is create your own collection class, probably inheriting from List<string> or List<MyType>, start by using its normal Sort method, later on override the Sort method with your own (for which I already gave the basic principles in another thread). :)

                    Luc Pattyn

                    :badger: :jig: :badger:

                    Have a look at my entry for the lean-and-mean competition; please provide comments, feedback, discussion, and don’t forget to vote for it! Thank you.

                    :jig: :badger: :jig:

                    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