Lean  $LEAN_TAG$
ComparisonOperator.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14 */
15 
16 using System;
17 
18 namespace QuantConnect.Util
19 {
20  /// <summary>
21  /// Utility Comparison Operator class
22  /// </summary>
23  public static class ComparisonOperator
24  {
25  /// <summary>
26  /// Compares two values using given operator
27  /// </summary>
28  /// <typeparam name="T"></typeparam>
29  /// <param name="op">Comparison operator</param>
30  /// <param name="arg1">The first value</param>
31  /// <param name="arg2">The second value</param>
32  /// <returns>Returns true if its left-hand operand meets the operator value to its right-hand operand, false otherwise</returns>
33  public static bool Compare<T>(ComparisonOperatorTypes op, T arg1, T arg2) where T : IComparable
34  {
35  switch (op)
36  {
37  case ComparisonOperatorTypes.Equals:
38  return arg1.CompareTo(arg2) == 0;
39  case ComparisonOperatorTypes.NotEqual:
40  return arg1.CompareTo(arg2) != 0;
41  case ComparisonOperatorTypes.Greater:
42  return arg1.CompareTo(arg2) == 1;
43  case ComparisonOperatorTypes.GreaterOrEqual:
44  return arg1.CompareTo(arg2) >= 0;
45  case ComparisonOperatorTypes.Less:
46  return arg1.CompareTo(arg2) == -1;
47  case ComparisonOperatorTypes.LessOrEqual:
48  return arg1.CompareTo(arg2) <= 0;
49  default:
50  throw new ArgumentOutOfRangeException(nameof(op), $"Operator '{op}' is not supported.");
51  }
52  }
53  }
54 }