I use this method called SearchConsequences to iterate through List<ValuesEO> of objects and perform some tasks, for getting values of particular fields, according to applied rules. I want to somehow simplify this code.
I want to switch (replace) everywhere in code the expression ValuesEO[i].powerR for other ValuesEO[i].otherField in the whole block of code.
At this time I do this just by block coping and changing it manually. So lets say, at the end, I have 5 blocks of really similar code blocks in this method. The only difference is in ValuesEO[i].otherField than ValuesEO[i].otherField2 ValuesEO[i].otherField3 … and so on.
I don’t like that block coping.
public Dictionary<Consequence,Cause> SearchConsequences(List<ResultsCatcher> smallTable, int n, ConnectHYSYS obj, int keyP, int keyR)//for one stream for one parameter
{
double threshold = 0.005;
Dictionary<Consequence,Cause> collection = new Dictionary<Consequence,Cause>();
//search in ValesE for each energy stream, for powerR
for (int i = 0; i < smallTable[n].ValuesE.Count; i++)
{
//sort the smallTable
smallTable.Sort((x, y) => x.ValuesE[i].powerR.CompareTo(y.ValuesE[i].powerR));
//get the index of first occurrence of powerR >= threshold, if there is nothing bigger than threshold, index is null
var tagged = smallTable.Select((item, ii) => new { Item = item, Index = (int?)ii });
int? index = (from pair in tagged
where pair.Item.ValuesE[i].powerR >= threshold
select pair.Index).FirstOrDefault();
//get needed information
if (index != null)
{
int id = Convert.ToInt16(index);
double newValue = smallTable[id].ValuesE[i].power;
double newValueR = smallTable[id].ValuesE[i].powerR;
TypeOfValue kindOf = TypeOfValue.power;
Consequence oneConsequence = new Consequence(obj.EnergyStreamsList[i], newValue, newValueR, kindOf);
Cause oneCause = new Cause();
oneCause.GetTableHeader(smallTable[id]);
collection.Add(oneConsequence,oneCause);
}
}
}
Maybe it is easy to accomplish that and somewhere this problem is discussed.
But I really even don’t know how to google it.
This is a ready made program for you that demonstrates how to move your criteria/property selection outside your examination function. Have a look to see how fields criterias are matched.