So here is a basic example and not the full code. I want to be able to refer to the specific variable in Symbol rather than have a bunch of if statements to know which values to add. I know i could make each instance of DataLine a list but that would not work for my overall goal.
public class DataLine
{
public int open;
public int close;
public int high;
public int low;
}
Public class Symbol
{
public string Code;
public string Name;
public DataLine Day;
public DataLine Week;
public DataLine Month;
}
public int AddValues(string lineName, ref List<Symbol> symbol)
{
int sum = 0;
for(int i = 0; i < symbol.Count - 1; i++)
{
if (lineName == "day")
{
sum = sum + symbol[i].Day.close
}
else if (lineName == "week")
{
sum = sum + symbol[i].Week.close
}
else if (lineName == "month")
{
sum = sum + symbol[i].month.close
}
}
return sum;
}
public void Main()
{
List<Symbol> symbol = new List<Symbol>();
//imagine here symbol has items added and variables in DataLine have values
int daysSum = AddValues("day", ref List<symbol>);
}
It sounds like what you really want is to accept a Func<Symbol, DataLine>
, or possibly a Func<Symbol, int>
. Although at that point, you don't really need a method, given how trivial (and value-free) that method would be using LINQ:
public int AddValues(Func<Symbol, int> extractor, List<Symbol> symbols)
{
return symbols.Sum(extractor);
}
You'd call it with:
int daysSum = AddValues(s => s.Day.close, symbol);
But without the method, you could just use:
int daysSum = symbol.Sum(s => s.Day.close);
... so really, why bother with the method?
Note that this is more flexible than just using s => s.Day
as it means you can easily sum the open, high or low instead of the close.
(For all the LINQ code, you just need a using
directive of using System.Linq;
at the top of your file.)
See more on this question at Stackoverflow