我不知道给这个问题的标题。如果你想出一些不错的东西并且相对于以下描述,请更改它:
我在列表中有一些数学运算:
A=11
B=1+2
C=A+E
D=B+A
E=C+B
但正如您所见,C=A+E
和E=C+B
存在循环引用问题。要报告此类问题,我的计算器应用程序将使用<CIR_REF>
替换循环引用。这将导致:
A=11
B=1+2
C=A+<CIR_REF>
D=B+A
E=<CIR_REF>+B
我无法为此形成逻辑。我能够达到的最接近的逻辑是遵循,但它甚至看起来不是非常优化的解决方案,我认为它不会产生预期的结果:
class Expression {
public char ID; //Like A,B,C,D (operand representing this expression)
public string value; //Contains the actual expression
}
List<Expression> expressions; //assigned outside the class containing this whole code.
public void ResolveCircularReference() {
for (int i = 0; i < expressions.Count; i++) {
List<string> Ops = Utility.GetOperands(expressions[i].value);
if (Ops.Count > 0) {
for (int j = 0; j < expressions.Count; j++) {
if (Ops.Contains(expressions[j].ID.ToString())) {
expressions[j].value = expressions[j].value.Replace(expressions[j].ID, "<CIR_REF>");
}
}
}
}
}
那么使用LINQ或LAMBDA表达式甚至是标准循环还有其他任何优化方法吗?
答案 0 :(得分:2)
你可以这样做:
扩展您的Expression
课程,另外添加另外两个IsCyclic
&amp; ConnectedBy
属性
public class Expression
{
public char Id { get; set; }
public string Value { get; set; }
public bool IsCyclic { get; set; }
public char ConnectedBy { get; set; }
}
获取操作数的方法:
private static IEnumerable<string> GetOperands(string value)
{
return Regex.Split(value, "[-+*/]");
}
获取输入值:
var expressions = new List<Expression>
{
new Expression{Id = 'A', Value = "11"},
new Expression{Id = 'B', Value = "1+2"},
new Expression{Id = 'C', Value = "A+E"},
new Expression{Id = 'D', Value = "B+A"},
new Expression{Id = 'E', Value = "C+B"}
};
现在,检测表达式是否是循环的,以及它们所连接的Id是:
foreach (var expression in expressions)
{
var operands = GetOperands(expression.Value);
var localCopy = expression;
foreach (var operand in
from operand in operands
from expression1 in expressions
where operand == expression1.Id.ToString()
&& expression1.Value.Contains(localCopy.Id)
select operand)
{
expression.IsCyclic = true;
expression.ConnectedBy = operand[0];
}
}
现在,使用ConnectedBy
"<CIR_REF>"
的特定值
foreach (var expression in expressions.Where(expression => expression.IsCyclic))
{
expression.Value = expression.Value.Replace(expression.ConnectedBy.ToString(), "<CIR_REF>");
}
那就是它。
输出: