Search code examples
c#databasestructure

How to create a structure with embedded fields?


I am looking for information about that in the internet but with no success. The goal is to realize a sort of dataset of 10 subject (sub_1, sub_2... sub_10), each of them has done 3 kind of activities (walk, run, jump) for three time each (trial_1... trial_3) with relative scores. I would like to access these information like:

variable = dataset.sub_1.jump.trial_2.score;

or, at least:

variable = dataset.sub[0].task[2].trial[1].score;

So, the structure would be a tree structure. Until now I only realized a structure with "parallel fields":

struct dataset
{
    public string[] sub;   // 1 to 10 subjects
    public string[] task;  // 1 to 3 tasks
    public string[] trial; // 1 to 3 trials
    public int score;      // the score of the above combination
}

Any idea?


Solution

  • This problem can be solved in many ways. My solution has one drawback, there is no check if user exceeded Score arrays capacity.

    I guess database tag has nothing to do with this question

    using System;
    using System.Linq;
    
    namespace ConsoleApp
    {
        public abstract class Task
        {
            public string Name { get; set; }
            public int TotalScore { get { return Score.Sum(); } }
            public int[] Score { get; set; } = new int[3];
        }
    
        public class Walk : Task { }
        public class Run : Task { }
        public class Jump : Task { }
    
        public class Subject
        {
            public Walk Walk { get; set; } = new();
            public Run Run { get; set; } = new();
            public Jump Jump { get; set; } = new();
            public int TotalScore { get { return Walk.TotalScore + Run.TotalScore + Jump.TotalScore; }}
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                var subject = new Subject();
    
                // Adding score to specific trials
                subject.Run.Score[0] = 50;
                subject.Run.Score[1] = 40;
                subject.Run.Score[2] = 60;
    
                subject.Jump.Score[0] = 40;
                subject.Jump.Score[1] = 80;
                subject.Jump.Score[2] = 100;
    
                // Output score of 1. trial for Walk task
                Console.WriteLine(subject.Walk.Score[0]);
    
                // Output total score as a sum of all trials for Jump task
                Console.WriteLine(subject.Jump.TotalScore);
    
                // Output total score as a sum of all trials in all tasks
                Console.WriteLine(subject.TotalScore);
    
                // ERROR CASE: this will be exception
                subject.Jump.Score[3] = 100;
            }
        }
    }