Home » c# » c# – Querying a list based on a string input

c# – Querying a list based on a string input

Posted by: admin March 4, 2020 Leave a comment


I’m trying to accomplish what I feel like should be a straightforward task, but have found it much more complicated than I expected.

Essentially, given:

public class MyObject
    public int A;
    public float B;
    public string C;

List<MyObject> objectList;

I would like to be able to read in strings something like:

"A < 1"
"B > 0.5"
"C = \"text\""

and for each of those get a List of items in objectList satisfying the requirement.

I’ve been working with LINQ queries like:

objectList.Where(obj => obj.A < 1)

so far, but am unable to figure out how to create queries like that with the field name.

Is there something straightforward that I am missing? Or is my whole approach here flawed?

How to&Answers:

I thinks you can use Expression tree, which you may be create own lambda expression and pass the it Where function.

For example please check these link:

Dynamically generate LINQ queries

Or you can use System.Linq.Dynamic namespace.:



You can apply AND operator (&&):

objectList.Where(obj => obj.A < 1 && obj.B > 0.5 && obj.C == "text").ToList();

More to read Filtering in LINQ


If you want to query based on string you can use System.Linq.Dynamic

objectList.Where("string predicate ..");