C# 在表达式树中的选择中创建选择
如何使用表达式树创建以下内容? 假设C# 在表达式树中的选择中创建选择,c#,reflection,lambda,expression-trees,C#,Reflection,Lambda,Expression Trees,如何使用表达式树创建以下内容? 假设索赔是索赔数据 var lastNames = claims.Select(p1 => p1.Advisors.Select(p2 => p2.LastName)); 使用以下示例类: public class ClaimData { public string name { get; set; } public IQueryable<AdvisorData> Advisors { get; set; } pu
索赔
是索赔数据
var lastNames = claims.Select(p1 => p1.Advisors.Select(p2 => p2.LastName));
使用以下示例类:
public class ClaimData
{
public string name { get; set; }
public IQueryable<AdvisorData> Advisors { get; set; }
public IQueryable<ActionData> Actions { get; set; }
}
public class AdvisorData
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class ActionData
{
public string Name { get; set; }
public string Comment { get; set; }
}
它只是为我返回正确的属性
谢谢您的错误出现在以下行:
var selectMethod = typeof(Queryable).GetMethods()
.Where(x => x.Name == "Select").First()
.MakeGenericMethod(property.PropertyType, typeof(string));
property.PropertyType
是IQueryable
。它应该是AdvisorData
。Select
的第一个通用参数是查找查询中一项的类型,而不是整个IQueryable
的类型。这意味着您的Select
调用需要传入一个IQueryable
,以匹配Select
参数
变化非常简单:
var selectMethod = typeof(Queryable).GetMethods()
.Where(x => x.Name == "Select").First()
.MakeGenericMethod(property.PropertyType.GetGenericArguments()[0],
typeof(string));
var selectMethod = typeof(Queryable).GetMethods()
.Where(x => x.Name == "Select").First()
.MakeGenericMethod(property.PropertyType, typeof(string));
var selectMethod = typeof(Queryable).GetMethods()
.Where(x => x.Name == "Select").First()
.MakeGenericMethod(property.PropertyType.GetGenericArguments()[0],
typeof(string));