You need to use reflection to get the list of properties and get a list of the values to, for example, apply the Max
Linq method:
public class Indicators
{
public Guid Id { get; set; }
public double? Indocator1 { get; set; }
public double? Indocator2 { get; set; }
public double? Indocator3 { get; set; }
public (string name, double? value) GetMaxIndicator()
{
var pairs = GetType().GetProperties()
.Where(p => p.PropertyType == typeof(double?))
.Select(p => new
{
name = p.Name,
value = (double?)p.GetValue(this)
});
string maxName= null;
double? maxValue = null;
foreach ( var item in pairs )
if ( maxValue == null || item.value > maxValue )
{
maxName= item.name;
maxValue = item.value;
}
return (maxName, maxValue );
}
}
Test
static private void Test()
{
var indicators = new Indicators();
indicators.Indocator1 = 10;
indicators.Indocator2 = null;
indicators.Indocator3 = 20;
var max = indicators.GetMaxIndicator();
Console.WriteLine($"{max.name} = {max.value}");
}
Output
Indicator3 = 20
This sample assumes that members are read-write and it returns the last found in case of duplicates, but you can return a list of named value tuples instead.
You can use that for fields with GetFields
.
Also you can combine both and you can filter the desired members using binding flags if, for example, you need non-public or static members.
Improvement for a cleaner and more robust design
You should prefer using a List
, or an array if the number of indicators is fixed.
The entity class
public class Indicator : IComparable
{
public string Name { get; set; }
public double? Value { get; set; }
public Indicator(string name, double? value = null)
{
Name = name;
Value = value;
}
int IComparable.CompareTo(object obj)
{
var other = obj as Indicator;
if ( other == null )
throw new ArgumentException("Object is not an Indicator");
if ( obj == null ) return 1;
if ( Value == null && other.Value == null )
return 0;
else
if ( Value == null )
return -1;
if ( other.Value == null )
return 1;
else
return Value.Value.CompareTo(other.Value.Value);
}
}
The collection class
public class Indicators
{
public Guid Id { get; set; }
public List<Indicator> Items { get; } = new List<Indicator>();
//or
public Indicator[] Items { get; } = new Indicator[IndicatorsCount];
}
Thus we can simply write:
var indicators = new Indicators();
indicators.Items.Add(new Indicator("Indicator1", 10));
indicators.Items.Add(new Indicator("Indicator2", null));
indicators.Items.Add(new Indicator("Indicator3", 20));
var max = indicators.Items.Max();
Console.WriteLine($"{max.Name} = {max.Value}");
That we can put in the class itself:
public class Indicators
{
public Guid Id { get; set; }
public double?[] Items { get; } = new double?[IndicatorsCount];
public double? MaxValue => Items.Max();
}