简体   繁体   中英

C#: one to many relation data type

For one-to-one I can use Hash or dictionary. Forexample Smith is 26 years old, Brown is 35 years old. This is clear. What about one to many? Forexample Smith is attending class01, class08, class12 and Brown is attending class01, class05, and class08. What are my alternatives and what is the best choice?

You can still use a Dictionary , but you need to make the value type a collection, ie: Dictionary<Person, IList<Class>> . This would allow you to store a list of classes per person.

You can use a Dictionary with a List as the second type.

For example, if you have a Student class and a Class class, you would have a

Dictionary<Student, List<Class>>

You can use Lookup<TKey, TValue> type. It works almost like dictionary but allows insert equal keys. Read more in MSDN article http://msdn.microsoft.com/en-us/library/bb460184.aspx .

You can have a hash or dictionary with a list as its value. Example:

var d = new Dictionary<string,List<string>> {
    { "Smith", new List<string> { "class01", "class08", "class12" } },
    { "Brown", new List<string> { "class01", "class05", "class08" } }
};

您可以使用

Dictionary<string, List<object>> OneToManyDictionary;

Create entity objects that are defined in a Person class. Have properties on the class to represent the various attributes and collections.

For example (pseudo-code)
Person class
  Age Property (int)
  Class Property (List)
... etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM