参数类型与将匿名表达式<func <t,u >>转换为非匿名表达式<func <t,u >>不匹配

时间:2019-04-23 11:06:23

标签: c# linq lambda expression visitor

想象一下,我们有三个这样的类:

public class ParentType {
    private ParentType() {}

    public int Id { get; protected set; }
    public SubType Sub { get; protected set; }
}

public class SubType{
    private SubType(){}

    public int Id { get; protected set; }
    public ICollection<ColSubType> ColSubs{get; protected set;}
}

public class ColSubType{
    private ColSubType(){}

    public int Id { get; protected set; }
    public SubType SubType { get; set; }
}

我有一个这样的匿名表达式:

x => new
{
   x.Id,
   Sub = new
   {
      x.Sub.Id,
      ColSubs = x.Sub.ColSubs.Select(u=> new {
             u.Id
      }).ToList()
   }
}

我需要将其转换为这样的非匿名表达式:

x => new ParentType()
{
   Id = x.Id,
   Sub = new SubType()
   {
      Id = x.Sub.Id,
      ColSubs = x.Sub.ColSubs.Select(u=> new ColSubs(){
             Id = u.Id
      }).ToList()
   }
}

感谢@IvanStoev对这个问题的回答:Variable 'x.Sub' of type 'SubType' referenced from scope '' but it is not defined error我能够转换简单的表达式,但是当我添加x.Sub.ColSubs.Select(...)时出现以下错误:

  

System.ArgumentException:参数类型不匹配

1 个答案:

答案 0 :(得分:2)

以下是您需要添加到递归Transform方法的代码,该方法可以精确地处理该场景,即检测Select,转换selector参数,修改TResult的{​​{1}}泛型类型参数,并使用新的Select进行调用,最后在目标不是selector的情况下调用ToList

IEnumerable<T>