Dynamic lambda expression for where clause

c# dynamic dynamic-linq lambda

Question

I have a dynamic list of objects on which I am using lambda expression where clause to filter items. For example, just consider that it have 3 properties, foo, bar and baz

class item // let this be current class in dynamic item list
{
    bool foo;
    string bar;
    string baz;
}

Now if I want to filter item list where foo is false I can use following expression

var filtered = itemList.Where("!foo");

I can even filter the list by strings value as

var filtered = itemList.Where("bar==\"value\""); \\all items with bar = value

What I want to actually check is if item in list have a specific string value not null of white space. I tried following code

var filtered = itemList.Where("!String.IsNullOrWhiteSpace(baz)");

It threw an error

Expression of type 'System.Func`2[DynamicType,System.Object]' cannot be used for parameter of type 'System.String' of method 'Boolean IsNullOrWhiteSpace(System.String)'

Though I succeeded to get result by following query

var filtered = itemList.Where("baz!=null && baz!=\"\"");

I wanted to confirm if there is a way I can use String.IsNullOrWhiteSpace() in this query.

1
0
1/13/2017 7:38:29 PM

Accepted Answer

You can replace "!String.IsNullOrWhiteSpace(baz)" with "!(baz == null || baz.Trim() == string.Empty)" and it should work.

0
1/13/2017 7:44:41 PM

Popular Answer

I have no problem using your expression - it works fine.

I have used this with objects and entities against an EF storage.

Expression of type 'System.Func`2[DynamicType,System.Object]' cannot be used for parameter of type 'System.String' of method 'Boolean IsNullOrWhiteSpace(System.String)'

So looking at the error, it is stating (moving the order around):

The method IsNullOrWhiteSpace, that returns a Boolean, expects a parameter of type System.String. But what was received was Expression of type System.Func``2[DynamicType,System.Object]'

It appears that you may have referenced an object rather than a string value for your comparison. However, without sample code for the objects you are using, and whether you are using objects, entities, or LinQ to SQL (which I haven't tried) we can only guess at what you have supplied for the expression.

Finally, what is a

'dynamic item list'?

Are you using Dynamic, or is it a normal List<Item>?



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow