简体   繁体   中英

Can I generate a linq expression dynamically in C#?

I've currently got a piece of Linq that looks something like this ;

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

where ItemsSource is an ObservableCollection of dynamics.

This works fine, but the problem I've got is that the ParentID is a property that can vary. Eg it could be named ParentPkey or ParentKey etc.

Can I create an expression where I can specify the property that I want to use in my comparison?

I've tried using dynamic linq but it doesn't work using a collection of dynamics, works fine with a collection of pocos.

Thanks...

why make the implementation itself dynamic? you could simply do a dynamic invocation!

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

or

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 ... I believe you should tell us more about your actual problem - I do not see any current need to implement sth - so, I believe your requirement is ill-defined!

it should not matter if query is dynamic linq or not

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

Check out PredicateBuilder of LinkKit @ http://www.albahari.com/nutshell/linqkit.aspx there are enough examples there as well

Responsibility of translation of an expression to corresponding sql lies with the linq provider, so make sure the provider you are using supports the relevant aspects

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

If you know the type of your items, you can use reflection :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM