如何整形动态连接返回的结果

时间:2016-01-20 17:07:30

标签: c# linq

public class Source
{
    public int SourceID;
    public int? SecurityId;
    public int? CUSIP;
    public string Text;
}

public class Destination
{
    public int DestinationID;
    public int? SecurityId;
    public int? CUSIP;
    public string Text;
}

IQueryable listleftJn = 
    listOfSources
    .AsQueryable()
    .GroupJoin(
        listOfDestinations.AsQueryable(),
        "new (outer.SecurityId as SecurityId, outer.CUSIP as CUSIP)",
        "new (inner.SecurityId as SecurityId, inner.CUSIP as CUSIP)",
        "new (outer as sources, group as destinations)")
    .SelectMany(
        "destinations",
        "new(outer as sources, inner as destinations)");

如何整形动态IQueryable listleftJn的结果并将其映射到类类型。这样我就可以使用Mapped类进一步使用。

1 个答案:

答案 0 :(得分:2)

我相信你可以使用我对Execution-Deferred IQueryable<T> from Dynamic Linq?

的答案中的方法

首先,从链接中添加相同的帮助方法

public static class DynamicQueryableEx
{
    public static IQueryable<TResult> Select<TResult>(this IQueryable source, string selector, params object[] values)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (selector == null) throw new ArgumentNullException("selector");
        var dynamicLambda = System.Linq.Dynamic.DynamicExpression.ParseLambda(source.ElementType, null, selector, values);
        var memberInit = dynamicLambda.Body as MemberInitExpression;
        if (memberInit == null) throw new NotSupportedException();
        var resultType = typeof(TResult);
        var bindings = memberInit.Bindings.Cast<MemberAssignment>()
            .Select(mb => Expression.Bind(
                (MemberInfo)resultType.GetProperty(mb.Member.Name) ?? resultType.GetField(mb.Member.Name),
                mb.Expression));
        var body = Expression.MemberInit(Expression.New(resultType), bindings);
        var lambda = Expression.Lambda(body, dynamicLambda.Parameters);
        return source.Provider.CreateQuery<TResult>(
            Expression.Call(
                typeof(Queryable), "Select",
                new Type[] { source.ElementType, lambda.Body.Type },
                source.Expression, Expression.Quote(lambda)));
    }
}

然后你可以使用这样的东西

var result = listleftJn.Select<ResultOfSOurceAndDestination>(
    "new (sources.SourceId as SourceId, destinations.DestinationID as DestinationID, sources.SecurityId as SecurityId, etc...)");

不要忘记使用sourcesdestinations访问者(您在SelectMany - "new(outer as sources, inner as destinations)"中定义的访问者)。我会在sourcedestination,或更短sd这两个地方使用,但一旦匹配就不重要。

更新:您的SelectMany投影中也存在问题。

"new(outer as sources, inner as destinations)"

应该是

"new(outer.sources as sources, inner as destinations)"