Need guidance towards evaluative boolean logic tree

拟墨画扇 提交于 2019-12-03 00:14:43

Your parsing of the expression ((Sex == Male AND Age == 25) OR (Sex == Female AND Status == Single)) AND IQ > 120 looks odd. I would parse it as:

* And
    * Or
        * And
            * ==
                * Sex
                * Male
            * ==
                * Eyes
                * Blue
        * And
            * ==
                * Sex
                * Female
            * ==
                * Status
                * Single
    * >
        * IQ
        * 120

The tree type would be :

Node
{
    bool evaluate ()
}

AndNode : Node
{
    Node left
    Node right

    bool evaluate ()
    {
        return left.evaluate () && right.evaluate ()
    }
}

// OrNode is similar

EqualsNode : Node
{
    Field field
    Value value

    bool evaluate ()
    {
        return field.value () == value
    }
}

// Likewise for <, >, etc

These kinds of queries are often presented as an ORed array of ANDed clauses. That is, a tabular format in which you read across multiple conditions ANDed together, and then read down to OR them. That leads to some repetition of conditions, but is easy for users to read, write, and understand. Your sample ((Sex == Male AND Age == 25) OR (Sex == Female AND Status == Single)) AND IQ > 120 would look like

Sex == Male   & Age == 25        & IQ > 120 
Sex == Female & Status == Single & IQ > 120 
High Performance Mark

You might want to Google for terms such as 'predicate calculus' and 'conjunctive normal form'.

I have to say that this is why database engines are built. You can do all that you require with set logic and you may even arrive at the result you are looking for, but theses are standard problems solved by databases and SQL. You can also look at linq for a in code solution.

Sounds like you need to create a user interface that allows the creation of a simple parse tree. When the presses GO you can then walk the tree and create a LINQ expression tree from that user interface structure. Execute the LINQ query and then process the results as needed. I would therefore recommend you read up on LINQ expression trees.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!