我使用这个方法SearchConsequences
来迭代List<ValuesEO>
对象并执行一些任务,以根据应用的规则获取特定字段的值。我想以某种方式简化这段代码。
我想在代码中的任何地方切换(替换)整个代码块中ValuesEO[i].powerR
其他的表达式。ValuesEO[i].otherField
目前,我只是通过阻止应对和手动更改来做到这一点。所以可以说,最后,我在这个方法中有 5 个非常相似的代码块。ValuesEO[i].otherField
唯一的区别在于ValuesEO[i].otherField2
ValuesEO[i].otherField3
...等等。
我不喜欢那种块应对。
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);
}
}
}
也许很容易做到这一点,并且在某个地方讨论了这个问题。但我真的什至不知道如何谷歌它。