Get max values of several int parameters

Viewed 237

I have a list of parameters to read, and need to get their max value. I am not talking about a List but about several int values :

int ColAssComm = Register.getImportExcelDSTV("AssComm")-1;
int ColAssDwg = Register.getImportExcelDSTV("AssDwg") - 1;
int ColAssGpe = Register.getImportExcelDSTV("AssGp") - 1;
int ColAssName = Register.getImportExcelDSTV("AssName") - 1;
int ColAssPrio = Register.getImportExcelDSTV("AssPrio") - 1;
int ColAssPds = Register.getImportExcelDSTV("AssPds") - 1;
int ColAssSurfPaint = Register.getImportExcelDSTV("AssSurfPaint") - 1;
int ColAssQty = Register.getImportExcelDSTV("AssQty") - 1;
int ColRepName = Register.getImportExcelDSTV("RepName") - 1;
int ColRepQty = Register.getImportExcelDSTV("RepQty") - 1;
int ColRepExecutionClass = Register.getImportExcelDSTV("RepExecutionClass") - 1;
int ColRepTreatment = Register.getImportExcelDSTV("RepTreatment");

And I need to do somthing like

int maxvalue = Max(ColAssComm,ColAssDwg..., ColRepTreatment)

Is there a way to do it all at once?

2 Answers

Another option would be to create a generic method like the following:

public T FindMax<T>(params T[] items)
{
    return items.Max();
}

Then you can pass a dynamic amount of parameters into the method, so you could just pass all your variables from your example into this method and get back the MAX of whatever type you wanted, this could work for integers and doubles and decimals... etc.

As suggested by @Idle_Mind you can use a dictionary like that:

using System.Collection.Generic;

string[] ParamNames =
{
  "AssComm", "AssDwg", "AssGp", "AssName", "AssPrio", "AssPds",
  "AssSurfPaint", "AssQty", "RepName", "RepQty", "RepExecutionClass", "RepTreatment"
};

Dictionary<string, int> ParamsData = new Dictionary<string, int>();

Thus we define once an array having a list of parameter's names needed.

Next we define a dictionary having param's names as key without using multiple vars.

Next we initialize the dictionary from the stored values.

foreach ( string paramName in ParamNames )
  ParamsData.Add(paramName, Register.getImportExcelDSTV(paramName) - 1);

Therefore we have a simple way to apply anything we need on the collection like Max.

using System.Linq;

int max = ParamsData.Values.Max();

Also we can access params using:

ParamsData["AssComm"] = 10;

We can of course define string variables to not write by string these names:

string ColAssCommName = "AssComm";
string ColAssDwgName = "AssDwg";
...

Doing that we write:

string[] ParamNames = { ColAssCommName, ColAssDwgName ...}

And:

ParamsData[ColAssCommName] = 10;

To save we write something like that:

foreach ( string paramName in ParamNames )
  Register.setImportExcelDSTV(paramName, ParamsData[paramName] + 1);
Related