使用对列表项的引用构造 C# Lambda 表达式
本文关键字:Lambda 表达式 引用 列表 | 更新日期: 2023-09-27 17:57:15
我需要构造一个动态的lambda表达式,如下所示: m => m.Data[0].Name
我有模型类:
public class GridItem
{
[Required]
[Display(Name = "Name")]
public string Name{ get; set; }
[Required]
[Display(Name = "Address")]
public string Password { get; set; }
[Display(Name = "Age")]
public string Age{ get; set; }
}
public class GridModelList
{
public List<GridItem> Data { get; set; }
public GridModelList()
{
Data = new List<GridItem>();
Data.Add(new GridItem() {Name = "Name", Address= "Address", Age= 1 });
Data.Add(new GridItem() {Name = "Name", Address= "Address", Age= 1 });
}
}
我试图这样解释它:
ParameterExpression fieldName = Expression.Parameter(typeof(TGridModel), "m");
MemberExpression fieldExpr = Expression.Property(fieldName, "m.Data.getItem(0).Name");
Expression<Func<TGridModel, object>> exp = Expression.Lambda<Func<TGridModel, object>>(fieldExpr, fieldName);
但是,我的问题是我不知道如何正确使用".getItem(0)",因为它给了我例外:
实例属性 'Data.get_Item(0)。未为类型"网格模型列表"定义名称
有关如何构建所需表达式的任何帮助m => m.Data[0].Name
将不胜感激!!
您需要将 Expression.Property 用于索引属性,如下所示
ParameterExpression fieldName = Expression.Parameter(typeof(TGridModel), "m");
var fieldDataExpr = Expression.Property(fieldName, "Data");
var fieldExpr = Expression.Property(fieldDataExpr, "Item", Expression.Constant(0));
var fieldNameExpr = Expression.Property(fieldExpr, "Name");
然后
Expression<Func<TGridModel, object>> exp = Expression.Lambda<Func<TGridModel, object>>(fieldNameExpr, fieldName);