Adding constraints to the model

The next step in the example is to add the linear constraints:

      // Add constraint: x + 2 y + 3 z <= 4
      model.AddConstr(x + 2 * y + 3 * z <= 4.0, "c0");

      // Add constraint: x + y >= 1
      model.AddConstr(x + y >= 1.0, "c1");

As with variables, constraints are always associated with a specific model. They are created using the AddConstr() or AddConstrs() methods on the model object.

We again use overloaded arithmetic operators to build linear expressions. The comparison operators are also overloaded to make it easier to build constraints.

The second argument to AddConstr gives the constraint name.

The Gurobi .NET interface also allows you to add constraints by building linear expressions in a term-by-term fashion:

  GRBLinExpr expr = 0.0;
  expr.AddTerm(1.0, x);
  expr.AddTerm(2.0, y);
  expr.AddTerm(3.0, z);
  model.AddConstr(expr, GRB.LESS_EQUAL, 4.0, "c0");
This particular AddConstr() signature takes a linear expression that captures the left-hand side of the constraint as its first argument, the sense of the constraint as its second argument, and a linear expression that captures the right-hand side of the constraint as its third argument. The constraint name is given as the fourth argument.

Try Gurobi for Free

Choose the evaluation license that fits you best, and start working with our Expert Team for technical guidance and support.

Evaluation License
Get a free, full-featured license of the Gurobi Optimizer to experience the performance, support, benchmarking and tuning services we provide as part of our product offering.
Academic License
Gurobi supports the teaching and use of optimization within academic institutions. We offer free, full-featured copies of Gurobi for use in class, and for research.
Cloud Trial

Request free trial hours, so you can see how quickly and easily a model can be solved on the cloud.