我可以在C#中动态生成linq表达式吗?

Mar*_*k D 1 c# linq lambda

我现在有一块看起来像这样的Linq;

List<dynamic> childrenToBeRemoved = this.ItemsSource.Where(o => o.ParentID == "1234").ToList();
Run Code Online (Sandbox Code Playgroud)

其中ItemsSource是动态的ObservableCollection.

这很好,但我遇到的问题是ParentID是一个可以变化的属性.例如,它可以命名为ParentPkey或ParentKey等.

我可以创建一个表达式,我可以在比较中指定要使用的属性吗?

我已经尝试过使用动态linq,但它不能使用动态集合,可以正常使用pocos集合.

谢谢...

And*_*air 5

为什么让实现本身动态?你可以简单地做一个动态调用!

IEnumerable<MyItem> result;
if (condition1)
{
    result = this.Items.Where(arg => arg.ProductId == "123");
}
else if (condition2)
{
    result = this.Items.Where(arg => arg.ProductPK == "123");
}
Run Code Online (Sandbox Code Playgroud)

要么

Func<Item, bool> predicate;
if (condition1)
{
    predicate = item => item.ProductId == "123";
}
else if (condition2)
{
    predicate = item => item.ProductPK == "123";
}
var result = this.Items.Where(predicate);
Run Code Online (Sandbox Code Playgroud)

Sooo ...我相信你应该告诉我们更多关于你的实际问题 - 我没有看到任何当前需要实施......所以,我相信你的要求是不明确的!


小智 5

查询是否为动态linq无关紧要

Expression<Func<Entity, int>> predicate = x => x.Id == myvalue;
from entity in _context.Entities.Where(predicate)
select entity;
Run Code Online (Sandbox Code Playgroud)

查看LinkKit的PredicateBuilder @ http://www.albahari.com/nutshell/linqkit.aspx, 那里也有足够的示例

将表达式转换为相应的sql的责任在于linq提供程序,因此请确保您使用的提供程序支持相关方面