Skip to main content
.NET Framework 4.6.2+

How to: Build Simple Criteria

  • 3 minutes to read

Using criteria objects you can precisely specify the objects that you want to appear in a collection. Criteria is a tree of objects representing a logical expression. Generally, a simple logical expression is comprised of a relational operator and its operands.

This topic demonstrates how to represent simple logical expressions in code. Please refer to How to Build Complex Criteria which is to do with complex logical expressions.

Building Simple Criteria - Example

With XPO, you have multiple options for building simple filter criteria. For instance, the same criteria which represents a simple logical expression (City <> “Chicago”) can be represented using two different notations as shown in code examples below.

  • You can pass the appropriate operands as parameters to the BinaryOperator‘s constructor.
// The criteria that represents a logical expression (City <> "Chicago") 
// is represented by the BinaryOperator and two operands.
CriteriaOperator criteria = new BinaryOperator(
    new OperandProperty("City"), new OperandValue("Chicago"),
    BinaryOperatorType.NotEqual
);

The main drawback of this way of writing criteria is that you have to write a lot of code. It can also be quite difficult to come up with complete hierarchies of operators that are frequently needed for complex expressions.

 

  • You can represent criteria as a human-readable string and parse it using the static CriteriaOperator.Parse method.
// The criteria that represents a logical expression (City <> "Chicago") is represented by a string.
CriteriaOperator criteria = CriteriaOperator.Parse("City != 'Chicago'");

The number of criteria operators available in XPO allow you to easily form logical expressions of considerable complexity.

The drawback here is that complex expressions basically stored in string variables in the code are not checked. If you are creating operator classes in code, it’s possible to make mistakes in field names, or comparing things that naturally can’t be compared. The whole string containing a query expression can’t be checked, and therefore can easily bring up runtime errors.

See Also