Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it better to create a List of new Objects or Dictionary?

I have a file with 2 columns and multiple rows. 1st column is ID, 2nd column is Name. I would like to display a Dropdown where I will show only all the names from this file.

I will only iterate through the collection. So what is the better approach? Is creating the objects more readable for other developers? Or maybe creating new objects is too slow and it’s not worth.

while (!reader.EndOfStream)
{
    var row = reader.ReadLine();
    var values = row.Split(' ');

    list.Add(new Object { Id = int.Parse(values[0]), Name = values[1] });               
}

or

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

while (!reader.EndOfStream)
{
    var row = reader.ReadLine();
    var values = row.Split(' ');

    dict.Add(int.Parse(values[0]), values[1]);              
}

>Solution :

Do I lose the speed in the case if I will create new objects?

You create new objects, so to speak, also while adding to the Dictionary<T>, you create new Key-Value pair of the desired type.
As you already mentioned in your question, the decision is made on primary

  • expected access pattern
  • performance considerations, which are the function also of access pattern per se.

If you need read-only array to iterate over, use List<T> (even better if the size of the data is known upfront use Type[] data, and just read it where you need it).

If you need key-wise access to your data, use Dictionary<T>.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading