Home > Software design >  c# Class object - What is the best way to store/retrieve a multiple-value list?
c# Class object - What is the best way to store/retrieve a multiple-value list?

Time:08-05

I'm teaching myself how to use classes in c#. I have a 'what's the best way' question I'm hoping someone with experience can give me guidance on.

Say I have a class object for a 'Teacher'. The class has members for the teacher's name, grade level, pay rate, and so on. I'd also like to store a variable-length list of properties for him. If he has various roles for different courses, like this:

English 1A       |  Instructor
English Lit      |  Advisor
Beginning Math   |  Substitute
Study Hall       |  Monitor
English 6b       |  Instructor

I'd like to store this information in his class object, and be able to access it in my code. I've tried an ArrayList, a HashTable, and a List<> (which doesn't let me store multiple columns, I don't think), but my approaches all feel like clunky workarounds. I'm leaning toward doing it this way:

Storing 2 columns into a List

This guy suggests creating a class object with two members and storing new instances of the class in a list. Good idea, but again, it has a 'workaround' feel to it.

Is there one "Right" way to do what I'm trying to do? Or can somebody suggest a more direct approach? Any thoughts are appreciated.

CodePudding user response:

This guy suggests creating a class object with two members and storing new instances of the class in a list.

This is the most common approach. Over time you might want to add fields to your notion of a 'Role' and having a class dedicated for it makes that easy.

You could use a more complicated approach like using a Dictionary<string, string>, a list of tuples, or a DataTable to store this kind of information in memory, but you usually would only use those approaches when you have a specific reason to use them (e.g. what you are modeling will never have additional properties/fields, or you are pulling from an API that returns DataTables for you).

  • Related