dotnet-dynamic-linq/PoweredSoft.DynamicLinq/ExpressionPathPart.cs

60 lines
2.1 KiB
C#
Raw Normal View History

2018-03-26 21:42:49 -04:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace PoweredSoft.DynamicLinq.Helpers
{
public class ExpressionPathPart
{
public Expression ParentExpression { get; set; }
2018-03-26 22:30:36 -04:00
public ParameterExpression ParameterExpression { get; set; }
public Expression PartExpression { get; set; }
2018-03-26 21:42:49 -04:00
2018-03-26 22:30:36 -04:00
public bool IsNullable() => TypeHelpers.IsNullable(PartExpression.Type);
public bool IsGenericEnumerable() => QueryableHelpers.IsGenericEnumerable(PartExpression);
public Type GenericEnumerableType() => PartExpression.Type.GenericTypeArguments.First();
public bool IsCallingMethod() => PartExpression is MethodCallExpression;
public Type GetToListType() => IsGenericEnumerable() ? GenericEnumerableType() : PartExpression.Type;
public bool IsParentGenericEnumerable() => QueryableHelpers.IsGenericEnumerable(ParentExpression);
public static List<ExpressionPathPart> Split(ParameterExpression param, string path)
2018-03-26 21:42:49 -04:00
{
var ret = new List<ExpressionPathPart>();
var parts = path.Split('.').ToList();
Expression parent = param;
parts.ForEach(part =>
{
var p = new ExpressionPathPart();
2018-03-26 22:30:36 -04:00
p.PartExpression = Expression.PropertyOrField(parent, part);
2018-03-26 21:42:49 -04:00
p.ParentExpression = parent;
2018-03-26 22:30:36 -04:00
p.ParameterExpression = param;
2018-03-26 21:42:49 -04:00
ret.Add(p);
2018-03-26 22:30:36 -04:00
if (p.IsGenericEnumerable())
{
param = Expression.Parameter(p.GenericEnumerableType());
parent = param;
}
else
{
parent = p.PartExpression;
}
2018-03-26 21:42:49 -04:00
});
return ret;
}
2018-03-26 22:30:36 -04:00
public LambdaExpression GetLambdaExpression()
{
var lambda = Expression.Lambda(PartExpression, ParameterExpression);
return lambda;
}
public Type ParentGenericEnumerableType() => ParentExpression.Type.GenericTypeArguments.First();
2018-03-27 09:43:07 -04:00
2018-03-26 21:42:49 -04:00
}
}