2

我目前有一块看起来像这样的 Linq;

List<dynamic> childrenToBeRemoved = this.ItemsSource.Where(o => o.ParentID == "1234").ToList();

其中 ItemsSource 是动态的 ObservableCollection。

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

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

我尝试过使用动态 linq,但它不能使用动态集合,但可以很好地与 pocos 集合一起使用。

谢谢...

4

4 回答 4

6

为什么要使实现本身动态化?您可以简单地进行动态调用!

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

或者

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);

Sooo ...我相信您应该告诉我们更多有关您的实际问题的信息-我认为当前不需要实施某事-所以,我相信您的要求定义不明确!

于 2012-05-08T11:44:07.817 回答
6

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

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

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

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

于 2012-05-08T11:52:28.780 回答
0

如果您知道物品的类型,则可以使用反射:

PropertyInfo parentProp = itemType.GetProperty("ParentKey or whatever");
List<dynamic> childrenToBeRemoved = this.ItemsSource.Where(o => Equals("1234", parentProp.GetValue(o, null))).ToList();
于 2012-05-08T11:41:28.530 回答
0

将您的 linq 表达式放入函数中,并将此属性作为参数传入。

于 2012-05-08T11:36:43.203 回答