Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# How to create a dynamic list/array

Tags:

arrays

c#

.net

list

Actually, I have this :

public ArrayList _albumId;
public ArrayList _albumName;
public ArrayList _nbPhotos;

And when I have a new album, I add a line on each ArrayList. Do you know something to do it with only one list or array ? Thanks

like image 995
Valentin C Avatar asked Feb 04 '26 00:02

Valentin C


2 Answers

First of all, don't use ArrayList - use generic List<T>.

Second - instead of having separate list for each attribute of album, create Album class with all required attributes, and keep albums in List<Album>:

public class Album
{
   public int Id { get; set; }
   public string Name {get; set; }
   public int CountOfPhotos {get; set; }
}

Adding new album:

_albums.Add(new Album { Id = 2, Name = "Foo", CountOfPhotos = 42 });

Where albums list declared as

List<Album> _albums = new List<Album>();
like image 85
Sergey Berezovskiy Avatar answered Feb 05 '26 14:02

Sergey Berezovskiy


Why keep information about the same thing broken apart into multiple arrays?

Create an Album object. Something like:

public class Album
{
    public int ID { get; set; }
    public string Name { get; set; }
    // other properties, etc.
}

And have a list of albums:

var albums = new List<Album>();

When adding a new album, add a new album:

var newAlbum = new Album
{
    ID = someValue,
    Name = anotherValue
}
albums.Add(newAlbum);

Keep information about an object encapsulated within that object, not strewn about in other disconnected variables.


As an analogy, consider the act of parking a car in a parking lot. With a collection of objects, the parking lot has a collection of spaces and each car goes into a space. Conversely, with separate arrays of values, the process for parking a car is:

  1. Take the car apart.
  2. Put the tires in the tire space, the windows in the window space, the doors in the door space, etc.
  3. When you want to get the car back, go around to all the spaces and find your parts. (Hope that you found the right ones.)
  4. Re-build the car.

Modeling encapsulated objects just makes more sense.

like image 34
David Avatar answered Feb 05 '26 14:02

David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!