2012-02-17 3 views
1

어딘가에 문자열 방정식을 실행할 수있는 함수가 있습니다. 예를 들어 "1 + 5"와 같은 문자열을 사용할 수 있습니다. 함수에 전달하면 응답을 반환합니다. 내 응용 프로그램에서는 데이터베이스에서 수식을 가져 와서 알 수없는 숫자 (예 : x, y 또는 z)를 응용 프로그램을 사용할 때 사용자가 입력 한 실제 숫자 (1,2,3,4,5 등)로 바꿉니다. 그러나 실행해야하는 수식 중 일부는 제곱근을 필요로합니다. Math.Sqrt() 함수가 포함 된 문자열을 전달하려고하면 정의되지 않은 함수라는 오류가 발생합니다. 이 함수를 인식하는 함수를 수정할 수있는 방법이 있습니까?데이터 테이블 인식 함수를 만드는 방법

이 함수는 데이터 테이블을 사용합니다. 다음은 코드입니다.

public static double executeFormula(string expression) 
{ 
    System.Data.DataTable table = new System.Data.DataTable(); 
    table.Columns.Add("expression", string.Empty.GetType(), expression); 
    System.Data.DataRow row = table.NewRow(); 
    table.Rows.Add(row); 
    return double.Parse((string)row["expression"]); 
} 

감사합니다!

+0

'온라인 어딘가에서'정확히 무엇을 사용하고 있습니까? – Randy

+0

나는 네가 무엇을 요구하고 있는지 정확히 모르겠다. 내가 어디서 얻었는지 알면, 문자열 방정식을 파싱 할 수있는 능력에 대한 질문에 대답하는 포럼에서 얻었습니다. 제가 사용하고있는 것이 무엇인지 묻는다면, 제가 학교에 가지고있는 프로젝트를위한 것입니다. 우리는 데이터베이스에서 가져온 수식을 구문 분석해야합니다. – Cityonhill93

+0

대신'string.Empty.GetType()'당신은'typeof (문자열)'을 쓸 수 있습니다. –

답변

3

nCalc을 사용하십시오.

그것은 당신이 말하는 것을 정확히 지원하며 아직 히트하지 않은 것들에 대해 확장 가능합니다.

+0

+1 - nCalc쪽으로 포인터 주셔서 감사합니다. 유용하게 보입니다! – dash

+0

@ 대시 : 그렇습니다. 우리는 두 가지 주요 문제를 해결하기 위해 그것을 사용합니다. 런타임까지 알 수없는 몇 가지 복잡한 수학 함수를 먼저 실행합니다. 두 번째는 페이지 처리를위한 간단한 규칙 엔진을 구현하는 데 사용된다는 것입니다. 아주 사용하기 쉽고 예쁜 부츠로 빨리 부팅 할 수 있습니다. – NotMe

+0

굉장합니다. 최고의 라이브러리! 정말 고마워! – Cityonhill93

0

사람들이 인식하고 사용할 수 있고 프로그램에서 구문 분석 할 수있는 "텍스트 기능"을 만들 수 있습니다. WolframAlpha 또는 MS Math 4.0을보십시오. 예를 들어 다음과 같이 할 수 있습니다.

if(str.IndexOf("sqrt")>-1) 
{ 
    //replace sqrt for the actual Math.Sqrt() function 
} 

행운을 비네!

2

당신이 작성한대로 대답은 '아니오'입니다. 보여주는 기능은 데이터 테이블에있는 DataColumn의 기능인 Expression 속성을 이용하는 것입니다. 문서에서

:

OPERATORS 

Concatenation is allowed using Boolean AND, OR, and NOT operators. You can use parentheses to group clauses and force precedence. The AND operator has precedence over other operators. For example: 

(LastName = 'Smith' OR LastName = 'Jones') AND FirstName = 'John' 

When creating comparison expressions, the following operators are allowed: 

< 

> 

<= 

>= 

<> 

= 

IN 

LIKE 

The following arithmetic operators are also supported in expressions: 

+ (addition) 

- (subtraction) 

* (multiplication) 

/(division) 

% (modulus) 

STRING OPERATORS 

To concatenate a string, use the + character. Whether string comparisons are case-sensitive or not is determined by the value of the DataSet class's CaseSensitive property. However, you can override that value with the DataTable class's CaseSensitive property. 

WILDCARD CHARACTERS 

Both the * and % can be used interchangeably for wildcards in a LIKE comparison. If the string in a LIKE clause contains a * or %, those characters should be escaped in brackets ([]). If a bracket is in the clause, the bracket characters should be escaped in brackets (for example [[] or []]). A wildcard is allowed at the beginning and end of a pattern, or at the end of a pattern, or at the beginning of a pattern. For example: 

"ItemName LIKE '*product*'" 

"ItemName LIKE '*product'" 

"ItemName LIKE 'product*'" 

Wildcards are not allowed in the middle of a string. For example, 'te*xt' is not allowed. 

PARENT/CHILD RELATION REFERENCING 

A parent table may be referenced in an expression by prepending the column name with Parent. For example, the Parent.Price references the parent table's column named Price. 

A column in a child table may be referenced in an expression by prepending the column name with Child. However, because child relationships may return multiple rows, you must include the reference to the child column in an aggregate function. For example, Sum(Child.Price) would return the sum of the column named Price in the child table. 

If a table has more than one child, the syntax is: Child(RelationName). For example, if a table has two child tables named Customers and Orders, and the DataRelation object is named Customers2Orders, the reference would be: 

Avg(Child(Customers2Orders).Quantity) 

AGGREGATES 

The following aggregate types are supported: 

Sum (Sum) 

Avg (Average) 

Min (Minimum) 

Max (Maximum) 

Count (Count) 

StDev (Statistical standard deviation) 

Var (Statistical variance). 

Aggregates are usually performed along relationships. Create an aggregate expression by using one of the functions listed above and a child table column as detailed in PARENT/CHILD RELATION REFERENCING above. For example: 

Avg(Child.Price) 

Avg(Child(Orders2Details).Price) 

불행하게도, 제곱근 당신이 사용할 수있는 기능 중 하나가 아닌

효과적으로, 당신이 SQL에서 찾을하려는 사업자의 많은 지원합니다. 그러나 DataTable을 사용하면 행을 순환하여 열 값에서 직접 SquareRoot를 계산할 수 있습니다. "MyNumber"라는 열이 있다고 가정 해보십시오. 당신이 원한다면 당신은 Extension 방법으로 기능 이런 종류의를 둘 수 있었다

myDataTable.Columns.Add(new DataColumn() { Name = "MySquareRoot", DataType = typeof(Double)}); 

foreach(DataRow row in myDataTable.Rows) 
{ 
    myDataTable["MySquareRoot"] = Math.Sqrt(Convert.ToDouble(myDataTable["MyNumber"])); 
} 

: 당신은 다음과 같은 일을 할 수 있습니다.

다른 방법으로 수식을 처리 할 수도 있습니다. DataTable을 사용하여 데이터를 모델링하는 대신 클래스를 사용할 수 있습니다. 클래스 자체는 데이터를 나타내는 속성 (또는 목록 또는 컬렉션)과 데이터에서 작동하는 메서드를 가질 수 있습니다. 그러면 C#에서 원하는 모든 함수를 사용할 수 있습니다.

0

CodePlex 프로젝트 flee을 살펴보십시오. Flee를 사용하면 런타임에 "sqrt(a^2 + b^2)"과 같은 문자열 표현식을 평가할 수 있습니다.

관련 문제