0

I have a linq query like that:

Elementos = From b In Elementos Where b.Value.IdGrupo = 0 Select b

"Elementos" is a dictionary(of long, MyObject). MyObject has approximately 50 properties.

The problem I have is that I have a new requirement to accept string parameter with a "where" condition. Something like "property1>10 and property2 like 'anystring' or property3<=25". (That means any property could have a condition. I have string and numeric properties.)

I'd like to keep using linq, adding the condition as it comes. I'm aware that it could produce an exception if the condition is misspelled or something, but that's acceptable (by try catchs). I wouldn't want to parse the string to build parameters or anything. Do I have a chance?

Thank you very much!

2 Answers 2

1

You can use Dynamic Linq:

Dim filter As String = "property1>10 and property2 like 'anystring' or property3<=25"
Dim results = Elementos.Where(filter)
Sign up to request clarification or add additional context in comments.

2 Comments

Hi! thank you for your answer. That's seems to be exactly what I need; however, I've downloaded the dynamic linq demo project, but when i add the dynamic.vb class into my project, every other object declared into system.* namespaces get unrecognized. I've tried to convert the example project into a library class, building a DLL and add it to my project, but, while im getting no error that way, even importing System.Linq.Dynamic into my class, i can't use elements.where("...") since i get an error (the function can't be called with those arguments). I appreciate any help! Thank you!
Hi, I've solved the previous issue renaming the dynamic class namespace. Now I'm trying to use wildcards in 'anystring'...
0

You could try something like this, You can construct the query by appending additional Where clauses. Each clause will be treated as an AND.

public class MyObject
{
    public String Bar {get;set;}
    public String Foo {get;set;}
}

var list = new[] { new MyObject { Foo= "Foo" }, new MyObject { Foo = "Foo", Bar = "Bar" }};
var query = list.Where(o => o.Foo == "Foo");
if(/* Some Condition */)
{
    query = query.Where(o => o.Bar == "Bar");
}

2 Comments

-1: This would only work if there was a very limited set of possible values for the condition; the fact the example given in the question is SQL(-ish) strongly implies that's not the case.
Hi, Thank you for your answer. Since I get a string condition, I don't see what would be /*some condition*/ without parsing the string?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.