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. Other Discussions
  3. The Weird and The Wonderful
  4. How to add a single item to an array

How to add a single item to an array

Scheduled Pinned Locked Moved The Weird and The Wonderful
pythoncomdata-structurestutorialcode-review
31 Posts 23 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.
  • M Marc Clifton

    List ccList = new List();
    ccList.Add(cc);
    foo.Items = ccList.ToArray();

    1. Create a list.
    2. Add the item to the list.
    3. Convert the list to an array.

    :sigh:

    Latest Article - Code Review - What You Can Learn From a Single Line of Code

    Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

    Artificial intelligence is the only remedy for natural stupidity. - CDP1802

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

    Someone who learned to "program in C# in 21 days"? :)

    Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

    1 Reply Last reply
    0
    • M Marc Clifton

      List ccList = new List();
      ccList.Add(cc);
      foo.Items = ccList.ToArray();

      1. Create a list.
      2. Add the item to the list.
      3. Convert the list to an array.

      :sigh:

      Latest Article - Code Review - What You Can Learn From a Single Line of Code

      Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

      Artificial intelligence is the only remedy for natural stupidity. - CDP1802

      G Offline
      G Offline
      GuyThiebaut
      wrote on last edited by
      #9

      How come nobody came up with the one line solution :rolleyes: ?

      foo.items = new List() { cc }.ToArray();

      “That which can be asserted without evidence, can be dismissed without evidence.”

      ― Christopher Hitchens

      K T D 3 Replies Last reply
      0
      • M Marc Clifton

        List ccList = new List();
        ccList.Add(cc);
        foo.Items = ccList.ToArray();

        1. Create a list.
        2. Add the item to the list.
        3. Convert the list to an array.

        :sigh:

        Latest Article - Code Review - What You Can Learn From a Single Line of Code

        Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

        Artificial intelligence is the only remedy for natural stupidity. - CDP1802

        P Offline
        P Offline
        PIEBALDconsult
        wrote on last edited by
        #10

        Quite. ToArray and ToList are code smells. As are pretty must all Toxxx methods. (ToString can be OK, but it's often misused as well.)

        L J 2 Replies Last reply
        0
        • M Marc Clifton

          List ccList = new List();
          ccList.Add(cc);
          foo.Items = ccList.ToArray();

          1. Create a list.
          2. Add the item to the list.
          3. Convert the list to an array.

          :sigh:

          Latest Article - Code Review - What You Can Learn From a Single Line of Code

          Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

          Artificial intelligence is the only remedy for natural stupidity. - CDP1802

          J Offline
          J Offline
          jsc42
          wrote on last edited by
          #11

          could be worse ...

          string[] oldarray = { "A", "B", "C" };
          string newitem = "D";
          oldarray = (String.Join(",", oldarray) + "," + newitem).Split(',');

          M 1 Reply Last reply
          0
          • P PIEBALDconsult

            Quite. ToArray and ToList are code smells. As are pretty must all Toxxx methods. (ToString can be OK, but it's often misused as well.)

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

            Convert.ToString is preferred ofcourse; As .ToString can be called on a null-object, causing an exception, where Convert.ToString would return an empty string without throwing an exception.

            Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

            1 Reply Last reply
            0
            • P PIEBALDconsult

              Quite. ToArray and ToList are code smells. As are pretty must all Toxxx methods. (ToString can be OK, but it's often misused as well.)

              J Offline
              J Offline
              Jon McKee
              wrote on last edited by
              #13

              If the only code being consumed is your code then I agree completely but ToArray can be useful when dealing with an external library that doesn't accept List. Forcing your own code to use a plain array simply to avoid a ToArray call could be much, much worse depending on how your code uses that array. I'd lob them in with what you said about ToString. It can be useful but is often misused.

              1 Reply Last reply
              0
              • G GuyThiebaut

                How come nobody came up with the one line solution :rolleyes: ?

                foo.items = new List() { cc }.ToArray();

                “That which can be asserted without evidence, can be dismissed without evidence.”

                ― Christopher Hitchens

                K Offline
                K Offline
                kalberts
                wrote on last edited by
                #14

                Did you do APL when you were a boy?

                G 1 Reply Last reply
                0
                • K kalberts

                  Did you do APL when you were a boy?

                  G Offline
                  G Offline
                  GuyThiebaut
                  wrote on last edited by
                  #15

                  Never heard of it until you asked - so I had to look at wikipedia.

                  “That which can be asserted without evidence, can be dismissed without evidence.”

                  ― Christopher Hitchens

                  K 1 Reply Last reply
                  0
                  • G GuyThiebaut

                    Never heard of it until you asked - so I had to look at wikipedia.

                    “That which can be asserted without evidence, can be dismissed without evidence.”

                    ― Christopher Hitchens

                    K Offline
                    K Offline
                    kalberts
                    wrote on last edited by
                    #16

                    As the Wikipedia article says: "In nearly all versions of APL, it is theoretically possible to express any computable function in one expression, that is, in one line of code" - the one-liner Game of Life is an excellent example. I learned APL as early as 1975-76, on one of the worlds earliest "PCs", the IBM 5100 - APL was almost exclusively an IBM thing then - and it was a well known joke that IBM was working on writing the entire OS360 (the first operating system for the 360/370 mainframe series) in a single line of APL :-) There are still elements of APL that I miss, in particular the "workspace" concept: You do your stuff in a sandpit where you throw in functions, variables and whatever stuff, and throw them out when no longer needed - while the "program" (workspace) running. On the 5100, you could save the entire workspace on disk in its current state, or you could declare selected variables as persistent. There were file system operations, but you rarely needed it. There have been languages with similar concepts (I believe Smalltalk comes close), but mainline programming 40 years later still are based on concepts that could be compared to "Of course you have to tell how much space to reserve for a file before starting to use it" (that's essentially how IBMs mainframe file systems were at the time). APL was so much more flexible and dynamic... I'm getting carried away. Maybe I tonight should curl up in my recliner in front of my fireplace with the old APL book, memorizing what the world was like when I was a youngster...

                    M T R 3 Replies Last reply
                    0
                    • K kalberts

                      As the Wikipedia article says: "In nearly all versions of APL, it is theoretically possible to express any computable function in one expression, that is, in one line of code" - the one-liner Game of Life is an excellent example. I learned APL as early as 1975-76, on one of the worlds earliest "PCs", the IBM 5100 - APL was almost exclusively an IBM thing then - and it was a well known joke that IBM was working on writing the entire OS360 (the first operating system for the 360/370 mainframe series) in a single line of APL :-) There are still elements of APL that I miss, in particular the "workspace" concept: You do your stuff in a sandpit where you throw in functions, variables and whatever stuff, and throw them out when no longer needed - while the "program" (workspace) running. On the 5100, you could save the entire workspace on disk in its current state, or you could declare selected variables as persistent. There were file system operations, but you rarely needed it. There have been languages with similar concepts (I believe Smalltalk comes close), but mainline programming 40 years later still are based on concepts that could be compared to "Of course you have to tell how much space to reserve for a file before starting to use it" (that's essentially how IBMs mainframe file systems were at the time). APL was so much more flexible and dynamic... I'm getting carried away. Maybe I tonight should curl up in my recliner in front of my fireplace with the old APL book, memorizing what the world was like when I was a youngster...

                      M Offline
                      M Offline
                      MikeTheFid
                      wrote on last edited by
                      #17

                      370 is one of those numbers where, if you cube the digits and add the results, it comes out to the original number. 3 x 3 x 3 = 27 7 x 7 x 7 = 343 0 x 0 x 0 = 0 27 + 343 + 0 = 370 (I worked for I've Been Moved from 1979-1987) :)

                      Cheers, Mike Fidler "I intend to live forever - so far, so good." Steven Wright "I almost had a psychic girlfriend but she left me before we met." Also Steven Wright "I'm addicted to placebos. I could quit, but it wouldn't matter." Steven Wright yet again.

                      K 1 Reply Last reply
                      0
                      • J jsc42

                        could be worse ...

                        string[] oldarray = { "A", "B", "C" };
                        string newitem = "D";
                        oldarray = (String.Join(",", oldarray) + "," + newitem).Split(',');

                        M Offline
                        M Offline
                        MikeTheFid
                        wrote on last edited by
                        #18

                        Consult your mental health professional immediately! ;)

                        Cheers, Mike Fidler "I intend to live forever - so far, so good." Steven Wright "I almost had a psychic girlfriend but she left me before we met." Also Steven Wright "I'm addicted to placebos. I could quit, but it wouldn't matter." Steven Wright yet again.

                        1 Reply Last reply
                        0
                        • M MikeTheFid

                          370 is one of those numbers where, if you cube the digits and add the results, it comes out to the original number. 3 x 3 x 3 = 27 7 x 7 x 7 = 343 0 x 0 x 0 = 0 27 + 343 + 0 = 370 (I worked for I've Been Moved from 1979-1987) :)

                          Cheers, Mike Fidler "I intend to live forever - so far, so good." Steven Wright "I almost had a psychic girlfriend but she left me before we met." Also Steven Wright "I'm addicted to placebos. I could quit, but it wouldn't matter." Steven Wright yet again.

                          K Offline
                          K Offline
                          kalberts
                          wrote on last edited by
                          #19

                          MikeTheFid wrote:

                          (I worked for I've Been Moved from 1979-1987)

                          So maybe you can confirm (or deny) what I've been told: An icon used in the 360 series marketing was a full circle, with one vertical radius drawn, like in a tradional "on/off" toggle button. Then I have heard said that the icon chosen for the 370 series was a bigger circle :-) People telling this story illustrate the new icon: A double circle, not consentric but touching where the radius crosses the rim. I can't remember ever seing this symbol in officiall IBM documentation, but maybe it was before I got into computing. (And, my only experience with IBM mainframes is for a single student project, on a remote machine I never saw.) Maybe this was an internal joke within IBM. Or maybe outside IBM. As we say where I live: If it isn't the truth, it sure is a great lie! ... I think it is so great that I sort of wish that it is true :-)

                          M O 2 Replies Last reply
                          0
                          • M Marc Clifton

                            List ccList = new List();
                            ccList.Add(cc);
                            foo.Items = ccList.ToArray();

                            1. Create a list.
                            2. Add the item to the list.
                            3. Convert the list to an array.

                            :sigh:

                            Latest Article - Code Review - What You Can Learn From a Single Line of Code

                            Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

                            Artificial intelligence is the only remedy for natural stupidity. - CDP1802

                            E Offline
                            E Offline
                            englebart
                            wrote on last edited by
                            #20

                            I think a better subject would be: How to create an array with a single item I thought this was going to be some sort of array concatenation/insertion N^3 algorithm.

                            M 1 Reply Last reply
                            0
                            • G GuyThiebaut

                              How come nobody came up with the one line solution :rolleyes: ?

                              foo.items = new List() { cc }.ToArray();

                              “That which can be asserted without evidence, can be dismissed without evidence.”

                              ― Christopher Hitchens

                              T Offline
                              T Offline
                              TNCaver
                              wrote on last edited by
                              #21

                              Am I missing something, or does your one-liner only create a single-element array with the new element, but doesn't add it to the original array?

                              If you think 'goto' is evil, try writing an Assembly program without JMP.

                              1 Reply Last reply
                              0
                              • E englebart

                                I think a better subject would be: How to create an array with a single item I thought this was going to be some sort of array concatenation/insertion N^3 algorithm.

                                M Offline
                                M Offline
                                Mark S Finn
                                wrote on last edited by
                                #22

                                Exactly. Something that actually answers the original question - like this:

                                 int\[\] existingArray = { 1, 12, 123, 1234 };
                                 existingArray = existingArray.Concat(new\[\] { 12345 }).ToArray();
                                
                                1 Reply Last reply
                                0
                                • M Marc Clifton

                                  List ccList = new List();
                                  ccList.Add(cc);
                                  foo.Items = ccList.ToArray();

                                  1. Create a list.
                                  2. Add the item to the list.
                                  3. Convert the list to an array.

                                  :sigh:

                                  Latest Article - Code Review - What You Can Learn From a Single Line of Code

                                  Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

                                  Artificial intelligence is the only remedy for natural stupidity. - CDP1802

                                  U Offline
                                  U Offline
                                  uoods
                                  wrote on last edited by
                                  #23

                                  Adding a single item to an array causes the entire array to be reallocated and copied. Simply put, the only array that can add an item is a linked list. Some of the suggested solutions use a different datatype List<> to create a copy of the original array, use its built in function ".Add" to insert an item, then creating a brand new array containing all the items. If the array needs to change again, then a whole new copy will be created in memory. This is all okay because it works, but it's not ideal. Copying a large array over and over only to add a single item at the end repeatedly will consume more CPU cycles (electricity and time) than necessary. Do what you have to to make it work, but then search for a better approach and adopt that when you find it. The highest performance method would be to use a linked list. In C++, linked lists can be very fast & cheap, but there are also some implementations in C#. The List<> object is a very nice implementation of a linked list, but there is also a LinkedList<> object that is optimized for adding items anywhere within the object.

                                  S 1 Reply Last reply
                                  0
                                  • G GuyThiebaut

                                    How come nobody came up with the one line solution :rolleyes: ?

                                    foo.items = new List() { cc }.ToArray();

                                    “That which can be asserted without evidence, can be dismissed without evidence.”

                                    ― Christopher Hitchens

                                    D Offline
                                    D Offline
                                    Danilo Nascimento Cunha
                                    wrote on last edited by
                                    #24

                                    var array = new[] { item };

                                    1 Reply Last reply
                                    0
                                    • K kalberts

                                      As the Wikipedia article says: "In nearly all versions of APL, it is theoretically possible to express any computable function in one expression, that is, in one line of code" - the one-liner Game of Life is an excellent example. I learned APL as early as 1975-76, on one of the worlds earliest "PCs", the IBM 5100 - APL was almost exclusively an IBM thing then - and it was a well known joke that IBM was working on writing the entire OS360 (the first operating system for the 360/370 mainframe series) in a single line of APL :-) There are still elements of APL that I miss, in particular the "workspace" concept: You do your stuff in a sandpit where you throw in functions, variables and whatever stuff, and throw them out when no longer needed - while the "program" (workspace) running. On the 5100, you could save the entire workspace on disk in its current state, or you could declare selected variables as persistent. There were file system operations, but you rarely needed it. There have been languages with similar concepts (I believe Smalltalk comes close), but mainline programming 40 years later still are based on concepts that could be compared to "Of course you have to tell how much space to reserve for a file before starting to use it" (that's essentially how IBMs mainframe file systems were at the time). APL was so much more flexible and dynamic... I'm getting carried away. Maybe I tonight should curl up in my recliner in front of my fireplace with the old APL book, memorizing what the world was like when I was a youngster...

                                      T Offline
                                      T Offline
                                      theoldfool
                                      wrote on last edited by
                                      #25

                                      "You can always tell an APL programmer, but not much."

                                      User: Technical term used by developers. See Idiot.

                                      1 Reply Last reply
                                      0
                                      • M Marc Clifton

                                        List ccList = new List();
                                        ccList.Add(cc);
                                        foo.Items = ccList.ToArray();

                                        1. Create a list.
                                        2. Add the item to the list.
                                        3. Convert the list to an array.

                                        :sigh:

                                        Latest Article - Code Review - What You Can Learn From a Single Line of Code

                                        Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

                                        Artificial intelligence is the only remedy for natural stupidity. - CDP1802

                                        M Offline
                                        M Offline
                                        Member 11561335
                                        wrote on last edited by
                                        #26

                                        If you think that's bad you should seen how I've seen multiple items get added to an array which the pseudo code was pretty much Create new array that's one item bigger than the old array Copy everything from the old array into the new one Add one item to the slightly larger array.(The new array is now full) repeat the previous 3 lines until you're done adding however many items you need to add. Yes, I've literally seen that done in C++ and damn is it inefficient. (Slow and fragments memory like crazy.)

                                        1 Reply Last reply
                                        0
                                        • K kalberts

                                          MikeTheFid wrote:

                                          (I worked for I've Been Moved from 1979-1987)

                                          So maybe you can confirm (or deny) what I've been told: An icon used in the 360 series marketing was a full circle, with one vertical radius drawn, like in a tradional "on/off" toggle button. Then I have heard said that the icon chosen for the 370 series was a bigger circle :-) People telling this story illustrate the new icon: A double circle, not consentric but touching where the radius crosses the rim. I can't remember ever seing this symbol in officiall IBM documentation, but maybe it was before I got into computing. (And, my only experience with IBM mainframes is for a single student project, on a remote machine I never saw.) Maybe this was an internal joke within IBM. Or maybe outside IBM. As we say where I live: If it isn't the truth, it sure is a great lie! ... I think it is so great that I sort of wish that it is true :-)

                                          M Offline
                                          M Offline
                                          MikeTheFid
                                          wrote on last edited by
                                          #27

                                          [IBM System/360 retrospective](https://it.toolbox.com/blogs/williamfavero/the-ibm-the-ibm-system-360-it-started-it-all-50-years-ago-today-and-the-world-has-never-been-the-same-since-040814) Near the bottom...

                                          Cheers, Mike Fidler "I intend to live forever - so far, so good." Steven Wright "I almost had a psychic girlfriend but she left me before we met." Also Steven Wright "I'm addicted to placebos. I could quit, but it wouldn't matter." Steven Wright yet again.

                                          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