Mark D
Mark D

Reputation: 289

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. E.g. 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...

Upvotes: 3

Views: 7596

Answers (4)

user57508
user57508

Reputation:

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!

Upvotes: 6

Julien
Julien

Reputation: 1192

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

Upvotes: 0

kalki
kalki

Reputation: 526

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

Upvotes: 7

Eamonn McEvoy
Eamonn McEvoy

Reputation: 8986

Put you linq expression into a function, and pass in this property as a parameter.

Upvotes: 0

Related Questions