ExpressionHelper.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* Copyright 2015-present MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * 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. using System.Linq;
  16. using System.Linq.Expressions;
  17. namespace MongoDB.Driver.Linq
  18. {
  19. internal static class ExpressionHelper
  20. {
  21. public static LambdaExpression GetLambda(Expression node)
  22. {
  23. if (node.NodeType == ExpressionType.Constant && ((ConstantExpression)node).Value is LambdaExpression)
  24. {
  25. return (LambdaExpression)((ConstantExpression)node).Value;
  26. }
  27. return (LambdaExpression)StripQuotes(node);
  28. }
  29. public static bool IsLambda(Expression node)
  30. {
  31. return StripQuotes(node).NodeType == ExpressionType.Lambda;
  32. }
  33. public static bool IsLambda(Expression node, int parameterCount)
  34. {
  35. var lambda = StripQuotes(node);
  36. return lambda.NodeType == ExpressionType.Lambda &&
  37. ((LambdaExpression)lambda).Parameters.Count == parameterCount;
  38. }
  39. public static bool IsLinqMethod(MethodCallExpression node, params string[] names)
  40. {
  41. if (node == null)
  42. {
  43. return false;
  44. }
  45. if (node.Method.DeclaringType != typeof(Enumerable) &&
  46. node.Method.DeclaringType != typeof(Queryable) &&
  47. node.Method.DeclaringType != typeof(MongoQueryable))
  48. {
  49. return false;
  50. }
  51. if (names == null || names.Length == 0)
  52. {
  53. return true;
  54. }
  55. return names.Contains(node.Method.Name);
  56. }
  57. public static bool TryGetExpression<T>(Expression node, out T value)
  58. where T : class
  59. {
  60. while (node.NodeType == ExpressionType.Convert ||
  61. node.NodeType == ExpressionType.ConvertChecked ||
  62. node.NodeType == ExpressionType.Quote)
  63. {
  64. node = ((UnaryExpression)node).Operand;
  65. }
  66. value = node as T;
  67. return value != null;
  68. }
  69. private static Expression StripQuotes(Expression expression)
  70. {
  71. while (expression.NodeType == ExpressionType.Quote)
  72. {
  73. expression = ((UnaryExpression)expression).Operand;
  74. }
  75. return expression;
  76. }
  77. }
  78. }