我有一個傳遞給First()orFirstOrDefault()呼叫的 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);
這是直截了當的,歡迎提出建議。
uj5u.com熱心網友回復:
您可以通過這種方式呼叫您的 Lambda 函式。
public GetRow()
{
T currentRow = CompareRow;
var firstRow = Rows.First(row => Lambda(row, CompareRow)); // get first row that matches Lambda
SelectedRow = firstRow;
}
這是另一個使用string引數的示例:
List<string> names = new() { "Alice", "Bob", "Charlie" };
string nameToMatch = "Alice";
Func<string, string, bool> Lambda = (left, right) => left.GetHashCode() == right.GetHashCode();
var alice = names.First(name => Lambda(name, nameToMatch));
Console.WriteLine($"Hi {alice}");
您可能在設定 Lambda 時遇到一些問題。型別看起來錯誤Func<Entity, Entity, bool>并不是Func<T, T, bool>因為對什么型別沒有限制T。
您可能需要考慮在 上添加一個約束T,可能是這樣的:
public class Model<T>
where T : Entity
{
public Func<Entity, Entity, bool> Lambda { get; set; }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/417521.html
標籤:
下一篇:按月和年計算活躍串列
