【发布时间】:2022-01-21 13:16:37
【问题描述】:
我有一个传递给 First() 或 FirstOrDefault() 调用的 lambda 表达式。
我想在 lambda 执行时动态注入一个参数值。
这是我现在的破解代码;它在运行的意义上“有效”。
ObservableCollection<T> Rows { get; set; }
T currentRow = Rows[0];
Template r = (Template)(object)currentRow;
Func<T, bool> p = e => ((Template)(object)e).TemplateId.Equals(r.TemplateId);
var firstRow = Rows.First(p);
我想要一些能正确处理通用 T 的东西
public class Model<T>
{
public ObservableCollection<T> Rows { get; set; } = {add rows here}
public Func<T, T, bool> Lambda { get; set; }
public T CompareRow {get; set;} // assume not null
public T SelectedRow { get; set; }
public GetRow()
{
T currentRow = CompareRow;
// First extension takes a lambda expression of Func<T,bool>
// SOMEHOW inject the runtime value of currentRow into lambda
// to convert Func<T, T, bool> to Func<T, bool>
var firstRow = Rows.First(Lambda); // get first row that matches Lamda
SelectedRow = firstRow;
}
}
public class MyModel: Model<Entity>
{
public void MyModel() : base()
{
// define the lambda expression with the concrete type of <Entity>
// each <Entity> type has different fields;
// so want to define a Lambda in the concrete class to validate the fields,
// but one that can be used in the generic base class.
Func<Entity, Entity, bool> p = (e,r) => e.TemplateId.Equals(r.TemplateId);
Lambda = p;
}
public SetRow() // called from somewhere
{
CompareRow = Rows.Last(); // assume Rows is not empty
}
public GetRow()
{
base.GetRow();
}
}
我找到了这些……
[https://stackoverflow.com/questions/16985310/convert-expressionfunct-t-bool-to-expressionfunct-bool] (这里面有额外的代码......所以这可以改进吗?)
[https://stackoverflow.com/questions/21922214/create-dynamic-linq-expression-for-select-with-firstordefault-inside] (这是特定于创建“选择” lambda)。
[https://www.codementor.io/@juliandambrosio/how-to-use-expression-trees-to-build-dynamic-queries-c-xyk1l2l82]
[https://stackoverflow.com/questions/63172233/dynamic-firstordefault-predicate-expression]
另外:如果有不同的调用方式
var firstRow = Rows.First(Lambda);
直截了当,欢迎提出建议。
【问题讨论】:
-
这是一个 lambda 表达式(是的,这是“d”之前的“b”) - 不是“lamda” ....