我使用这个名为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);
}
}
}
也许很容易实现这个问题并讨论这个问题。 但我甚至不知道如何谷歌。
答案 0 :(得分:0)
这是一个现成的程序,演示如何在您的考试功能之外移动您的标准/属性选择。看看如何匹配字段标准。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
namespace Test
{
class Program
{
public class PowerValues
{
public double power;
public double powerR;
public double lightbulbs;
public double lightbulbsR;
}
public static void DoSomething(IEnumerable<PowerValues> powerValues, Func<PowerValues, double> criteria, double treshhold)
{
var flaggedElements = powerValues.Where(e => criteria(e) > treshhold);
foreach (var flagged in flaggedElements)
{
Console.WriteLine("Value flagged: {0}", criteria(flagged));
}
}
public static void Main(string[] args)
{
List<PowerValues> powerValues = new List<PowerValues>();
powerValues.Add(new PowerValues(){power=10, powerR=0.002, lightbulbs = 2, lightbulbsR = 2.006});
powerValues.Add(new PowerValues(){power=5, powerR=0.004, lightbulbs = 4, lightbulbsR = 2.09});
powerValues.Add(new PowerValues(){power=6, powerR=0.003, lightbulbs = 3, lightbulbsR = 2.016});
Console.WriteLine("Power matching criteria . . . ");
DoSomething(powerValues, (e) => e.powerR, 0.003);
Console.WriteLine("Lightbulbs matching criteria . . . ");
DoSomething(powerValues, (e) => e.lightbulbs, 3);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
答案 1 :(得分:-2)