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

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

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

其中ItemsSource是动态的ObservableCollection。

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

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

我尝试过使用动态linq,但它不能使用动态集合,与pocos集合工作正常。

谢谢…

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

 Expression> 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提供程序,因此请确保您使用的提供程序支持相关方面

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

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

要么

 Func predicate; if (condition1) { predicate = item => item.ProductId == "123"; } else if (condition2) { predicate = item => item.ProductPK == "123"; } var result = this.Items.Where(predicate); 

Sooo …我相信你应该告诉我们更多关于你实际问题的信息 – 我认为当前没有需要实施……所以,我相信你的要求是不明确的!

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

如果您知道项目的类型,可以使用reflection:

 PropertyInfo parentProp = itemType.GetProperty("ParentKey or whatever"); List childrenToBeRemoved = this.ItemsSource.Where(o => Equals("1234", parentProp.GetValue(o, null))).ToList();