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?
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;
}
}
}
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
public class Trial
{
public Trial(int score)
{
Score = score;
}
public int Score { get; set; }
}
public class Task
{
public List<Trial> Trials { get; } = new List<Trial>();
}
public class Subject
{
public Dictionary<string, Task> Tasks { get; } = new Dictionary<string, Task>();
public Subject()
{
Tasks.Add("walk", new Task());
Tasks.Add("run", new Task());
Tasks.Add("jump", new Task());
}
}
class Program
{
static void Main(string[] args)
{
Subject player1 = new Subject();
player1.Tasks["run"].Trials.Add(new Trial(score: 3));
Console.WriteLine(player1.Tasks["run"].Trials[0].Score);
}
}
}
Maybe a class for everything is too much, but maybe you want to add a description property for tasks one day or a timestamp for the trial. Then it's ok.
public class Subject
{
private Dictionary<string,Activity> _activities { get; }= new Dictionary<string, Activity>();
public Activity this[string activity]
{
get
{
if (!_activities.Keys.Contains(activity))
_activities[activity] = new Activity();
return _activities[activity];
}
set
{
_activities[activity] = value;
}
}
public int Score => _activities.Values.Sum(x => x.Score);
}
public class Activity
{
private Dictionary<int, Trial> _trials { get; } = new Dictionary<int, Trial>();
public Trial this[int trial]
{
get
{
if (!_trials.Keys.Contains(trial))
_trials[trial] = new Trial();
return _trials[trial];
}
set
{
_trials[trial] = value;
}
}
public int Score => _trials.Values.Sum(x => x.Score);
}
public class Trial
{
public int Score { get; set; }
}
public class Answer
{
public void DoSomething()
{
Subject Mindy = new Subject();
Mindy["curling"][1].Score = 5;
Mindy["bowling"][1].Score = 290;
Console.WriteLine(Mindy.Score);
}
}
This is what I would guess you think you need... but from your question I think you're still new to C# and might want to rethink your concept. It looks like a very database-oriented way of looking at the problem, so maybe you might want to take a look at dapper to more closely match your database.
Also, avoid using the classname Task, this can imo only cause confusion if you ever start using multithreading (System.Threading.Task is a .NET framework component)
I created a trading system with an adaptive moving average on the average true range but the program reports this error to me
the modifier public is not valid for this item
at line 21 of the code
public int avgTrueRange.value1 { get; set; }
I tried to change public but it always reports this error.
this is the code :
public class MediaMobileAdattiva : SignalObject
{
public MediaMobileAdattiva(object _ctx): base(_ctx)
{
Range = 14;
FirstLength = 10;
AvgTrueRange.value1 = 1;
}
private IOrderMarket buy_order;
public int Range { get; set; }
public double FirstLength { get; set; }
public int AvgTrueRange.value1 { get; set; }
private double FirstAverage()
{
if (AverageTrueRange < AvgTrueRange.value1)
return FirstLength;
}
protected override void Create()
{
// create variable objects, function objects, order objects
buy_order = OrderCreator.MarketNextBar(new SOrderParameters(Contracts.Default, EOrderAction.Buy));
}
protected override void StartCalc()
{
// assign inputs
}
protected override void CalcBar()
{
// strategy logic
if (Bars.CurrentBar > 1)
{
switch (FirstAverage)
{
case FirstLength:
return 1;
}
}
if (Bars.CurrentBar > 1 && Bars.Close.CrossesOver(FirstAverage, ExecInfo.MaxBarsBack)
{
switch (FirstLength)
{
case 1:
buy_order.Send(Bars.Close[0]);
}
}
}
}
What you need is to make a struct for AvgTrueRange:
public struct Range
{
public int value1 {get; set;}
}
and change:
public int AvgTrueRange.value1 { get; set; }
to
public Range AvgTrueRange { get; set; }
Your code still won't compile btw but I don't really understand what you are trying to do in this line:
if (AverageTrueRange < AvgTrueRange.value1)
Also, change:
switch (FirstAverage)
{
case FirstLength:
return 1;
}
to
var avg = FirstAverage();
int? result = avg switch
{
var avg when avg == FirstLength => 1,
_ => null
};
if (result.HasValue) return result.Value;
as cases can only be constant values.
Im using Get; and Set; im trying to make a round counter when user inputs Rounds, Minutes, and seconds. Ive managed to create the buttons and input using Get; Set; ... the problem is when the time reaches 0 for minutes and seconds it doesnt reset the minutes and seconds to the original value the user entered the first time, it just keeps it at 0.... Please help.. I didnt add the button or timer start code that all works just the get set problem
class User
{
public static int Rounds { get; set; }
public static int InputRounds { get; set; }
public static int Sec { get; set; }
public static int Min { get; set; }
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e){
User.sec--;
if(User.sec <= 0)
{
User.Min--;
}
if(User.Min <= 0)
{
User.Rounds++;
}
if(User.Rounds >= User.InputRounds) // User.Input is the first value the user input
{
User.Min = ????; // This is my problem with the question marks
User.Sec = ????; // Im trying to set the value back to the users value entered
User.Rounds++; // then add 1 round
}
}
Maybe you just need to refactor your User class, and please don't use static properties unless necessary.
public class User
{
private int oMin;
private int oSec;
public User(int min, int sec, int maxRounds)
{
Min = min;
oMin = min; // Saving Original Values
Sec = sec;
oSec = sec; // Saving Original Values
MaxRounds = maxRounds;
}
public int Rounds { get; private set; }
public int MaxRounds { get; }
public int Sec { get; private set; }
public int Min { get; private set; }
public void ReduceSec()
{
Sec--;
if (Sec <= 0)
{
Min--;
}
if (Min <= 0)
{
Rounds++;
}
if (Rounds >= MaxRounds)
{
Min = oMin;
Sec = oSec;
Rounds++;
}
}
}
may I ask (as a novice) how do I call a method of a namespace, from another? Thank you for setting up an example if possible..
For example: (1) how do I set the properties of the MY_PRIMARY class to use them and (2) how do I call the AddNumbers method while in the MY_SECONDARY namespace? Thank you..
using.. etc
namespace MY_PRIMARY
{
public partial class SomethingHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
class Program
{
private static void Main()
{
// some code here.. and..
public int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
return result;
}
}
};
namespace MY_SECONDARY
{
public partial class SomethingElseHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
class Program
{
static void Main()
{
// some code here..
}
// and..
Program outer = new Program();
outer.AddNumbers(3, 18); // <--- this is failing..
}
}
;
Namespaces are meant to group objects semantically. I'm kind of confused why you have 2 program classes. It would make more sense to have one class library, and one program. Anyway...
Suppose you have an Object1 in namespace Program.First,
And an Object2 in Program.Second
Object2 has a method named someMethod.
What you would do to call this method is
a) either add "using Program.Second", on you first class.
b) make an instance of Program.Second.Object2, and call the method on that.
https://www.programiz.com/csharp-programming/namespaces
So suppose you want to make an object of Program() do this:
using System;
namespace MY_PRIMARY
{
public partial class SomethingHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
public class Program
{
public int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
return result;
}
}
}
namespace MY_SECONDARY
{
public partial class SomethingElseHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
class Program
{
static void Main()
{
MY_PRIMARY.Program outer = new MY_PRIMARY.Program();
outer.AddNumbers(3, 18);
}
}
}
(EDIT) updated my answer, i copied your code and saw that your namespaces were not closed off, therefor, you had nested namespaces, and classes in there. plus, some of the code was directly in your class instead of in a function.
Also, don't define 2 Main() methods, that's the entrypoint of the application.
...A little modification in POSITIONS of functions and classes... please, see:
using Alias = MY_PRIMARY.Program;
namespace MY_PRIMARY
{
public partial class SomethingHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
public class Program
{
private static void Main()
{
// some code here.. and..
}
public int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
return result;
}
};
namespace MY_SECONDARY
{
public partial class SomethingElseHere
{
public Boolean holiday { get; set; } = false;
public int age { get; set; } = 18;
//etc...
}
class Program
{
static void Main()
{
// some code here..
// and..
Alias outer = new Alias();
outer.AddNumbers(3, 18); // <--- OKAY...
}
}
}
}
See more:
Using namespaces (C# Programming Guide)
Let's say I have a class StockMarket which has a list of Companies.
class StockMarket : IStock
{
private static List<IObserverPush> observersPush;
private static List<IObserverPull> observersPull;
public static List<Company> Companies { get; private set; }
public StockMarket()
{
observersPush = new List<IObserverPush>();
observersPull = new List<IObserverPull>();
Companies = new List<Company>() { new Company("Unilever", "UNA", 47.72, 0.77, 1.63, -3.45, "135B"),
new Company("ING Groep", "INGA", 13.40, -0.07, -0.50, -12.38, "60.4B"),
new Company("ArcelorMittal", "MT", 29.50, 0.14, 0.48, 36.05, "54.6B"),
new Company("ASML Holding", "ASML", 167.40, 2.00, 1.21, 36.49, "53.3B"),
new Company("Heineken", "HEIA", 87.66, -0.02, -0.02, 2.80, "49B"),
new Company("RELX", "REN", 18.15, 0.17, 0.95, -0.22, "38.9B"),
new Company("Philips", "PHIA", 35.49, 0.17, 0.47, 7.61, "33.3B"),
new Company("Unibail Rodamco", "UL", 196.40, -0.15, -0.08, -16.78, "20.3B"),
new Company("Akzo Nobel", "AKZA", 75.68, -0.16, -0.21, 0.33, "19.4B"),
new Company("Altice", "ATC", 7.58, 0.16, 2.16, -66.30, "17.6B")};
Thread thread = new Thread(SimulateMarket);
thread.Start();
}
public void Subscribe(IObserverPull o)
{
observersPull.Add(o);
o.UpdateMarket();
}
public void Unsubscribe(IObserverPull o)
{
observersPull.Remove(o);
}
public void Subscribe(IObserverPush o)
{
observersPush.Add(o);
o.UpdateMarket(Companies);
}
public void Unsubscribe(IObserverPush o)
{
observersPush.Remove(o);
}
public void NotifyObservers()
{
foreach(IObserverPush o in observersPush)
{
o.UpdateMarket(Companies);
}
foreach(IObserverPull o in observersPull)
{
o.UpdateMarket();
}
}
public void SimulateMarket()
{
while(observersPush.Count + observersPull.Count > 0)
{
//randomly change property values of companies
//and notify the observers about the changes
}
}
}
Company class has some properties.
public class Company
{
public string Name { get; private set; }
public string Symbol { get; private set; }
public double Price { get; set; }
public double Change { get; set; }
public double ChangePercentageDay { get; set; }
public double ChangePercentageYear { get; set; }
public string Capital { get; private set; }
public Company(string name, string symbol, double price, double change, double changePercentageDay,
double changePercentageYear, string capital)
{
Name = name;
Symbol = symbol;
Price = price;
Change = change;
ChangePercentageDay = changePercentageDay;
ChangePercentageYear = changePercentageYear;
Capital = capital;
}
}
The Forms have references to the StockMarket and they use it to retrieve data about the companies and to display it.
Form 1
public partial class ConcreteObserverPush : Form, IObserverPush
{
private StockMarket stockMarket;
public ConcreteObserverPush()
{
InitializeComponent();
stockMarket = new StockMarket();
stockMarket.Subscribe(this);
}
public void UpdateMarket(List<Company> companies)
{
stockMarketListView.Items.Clear();
foreach(Company c in companies)
{
ListViewItem item = new ListViewItem(c.Symbol);
item.SubItems.Add(c.Price.ToString());
item.SubItems.Add(c.Change.ToString());
item.SubItems.Add(c.ChangePercentageDay.ToString() + "%");
stockMarketListView.Items.Add(item);
}
}
private void ConcreteObserverPush_FormClosing(object sender, FormClosingEventArgs e)
{
stockMarket.Unsubscribe(this);
}
}
Form 2
public partial class ConcreteObserverPull : Form, IObserverPull
{
private StockMarket stockMarket;
public ConcreteObserverPull()
{
InitializeComponent();
stockMarket = new StockMarket();
stockMarket.Subscribe(this);
}
public void UpdateMarket()
{
stockMarketListView.Items.Clear();
foreach (Company c in StockMarket.Companies)
{
ListViewItem item = new ListViewItem(c.Symbol);
item.SubItems.Add(c.Name);
item.SubItems.Add(c.Price.ToString());
item.SubItems.Add(c.Change.ToString());
item.SubItems.Add(c.ChangePercentageDay.ToString() + "%");
item.SubItems.Add(c.ChangePercentageYear.ToString() + "%");
item.SubItems.Add(c.Capital);
stockMarketListView.Items.Add(item);
}
}
private void ConcreteObserverPull_FormClosing(object sender, FormClosingEventArgs e)
{
stockMarket.Unsubscribe(this);
}
}
The problem is that if the Form gets the list of companies through the property on StockMarket it can change their state. However, I want only StockMarket to have the ability to change the state of the company.
So what would be the best way to share Company state with Form when requested and preventing the Form from modifying it.
I know that a possible solution would be to return clones of Company objects, but I believe there should be a better solution.
Any help is appreciated!
The general gist of this would be to make your Company object immutable. Then you would add methods to the StockMarket object to manipulate the Company list and replace entries with new ones when you want to change a value.
Here's a quick example put together in LINQPad of making the Company class immutable and adding an UpdatePrice method to the StockMarket class.
Whether you want to be able to manipulate the Companies property from outside the StockMarket can be handled by returning the list as ReadOnlyCollection so that it's size can't be manipulated by a consumer.
void Main()
{
var sm = new StockMarket();
sm.Companies.Add(new Company("Test", "TST", 50, 0));
sm.UpdatePrice("Test", 45);
var testCompany = sm.Companies.First(x => x.Name == "Test");
Console.WriteLine($"{testCompany.Name},{testCompany.Symbol},{testCompany.Price},{testCompany.Change}");
//Output: Test,TST,45,-5
}
class StockMarket
{
public List<Company> Companies { get; private set; } = new List<Company>();
public void UpdatePrice(string name, double price) {
var index = Companies.FindIndex(x => x.Name == name);
if(index >= 0)
{
var previous = Companies[index];
Companies[index] = new Company(previous.Name, previous.Symbol, price, price - previous.Price);
}
}
}
class Company
{
public Company(string name, string symbol, double price, double change) {
Name = name;
Symbol = symbol;
Price = price;
Change = change;
}
public string Name { get; }
public string Symbol { get; }
public double Price { get; }
public double Change { get; }
///...
}
This would be a solution:
Create the Company class as a Private Inner Class inside of the StockMarket class, that way it'd only be accessible inside of it, and then provide an interface that only includes the get of all the properties and make Company implement it. You would have to make StockMarket's Company list to be the Interface's type.
Any modification you'd have to do you'd do it by casting the interface's List objects into the original class type.
Example:
class Program
{
public static StockMarket stockMarket = new StockMarket();
static void Main(string[] args)
{
}
}
public interface ICompany
{
string Name { get; }
}
public class StockMarket
{
public StockMarket()
{
Companies = SomeWildFunctionThatRetrievesAllCompanies();
}
public void OneWildFunctionThatModifiesACompany()
{
Company dunno = (Company)Companies[0];
dunno.Name = "Modification Made Possible";
}
private List<ICompany> SomeWildFunctionThatRetrievesAllCompanies()
{
return new List<ICompany>(new List<Company>());
}
public List<ICompany> Companies { get; private set; }
private class Company : ICompany
{
public string Name { get; set; }
}
}
Try this:
class Company
{
public Company(Type type,string name,string symbol,double price, double change)
{
if (type.Name == "StockMarket")
{
Name = name;
Symbol = symbol;
Price = price;
Change = change;
}
}
private string Name { get; set; }
private string Symbol { get; set; }
private double Price { get; set; }
private double Change { get; set; }
///...
}
This will allow you to change the state only if the type is StockMarket
like:
class StockMarket
{
public List<Company> Companies { get; set; }
public StockMarket()
{
Companies = new List<Company>();
}
public StockMarket someMethod()
{
//You can change the state here
StockMarket s = new StockMarket();
s.Companies.Add(new Company(this.GetType(), "aa", "_", 123, 1234));
return s;
}
//...
}
Now you cannot change the state here:
public partial class Observer: Form
{
private StockMarket stockMarket;
public ConcreteObserverPull()
{
InitializeComponent();
stockMarket = new StockMarket();
//Here you cannot change the state
stockMarket.Companies.Add(new Company(this.GetType(), "aa", "_", 123,12));
}
//...
}
Sorry, I don't know C#, but as an idea, you can wrap returned entities with decorator or proxy, which will throw an exception in case of trying to modify state of a company.
Returning clones with fields set as readonly is the safest way to go.