想象一下,我们有三个这样的类:
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:参数类型不匹配
答案 0 :(得分:2)
以下是您需要添加到递归Transform
方法的代码,该方法可以精确地处理该场景,即检测Select
,转换selector
参数,修改TResult
的{{1}}泛型类型参数,并使用新的Select
进行调用,最后在目标不是selector
的情况下调用ToList
:
IEnumerable<T>