Dynamic query in LINQ

后端 未结 5 1308
不思量自难忘°
不思量自难忘° 2021-02-11 06:56

How do I write a dynamic query for Linq, if I have say Customer class which holds the fields:

string name
string address
int phoneno

I have to

5条回答
  •  梦如初夏
    2021-02-11 07:29

    Check out this http://www.albahari.com/nutshell/predicatebuilder.aspx, it allows for strongly typed predicate building, it can be really nice. If you want actually dynamic string built predicates than you can use the LINQ Dynamic Query Library provided by ScottGu.

    Both will accomplish what you want although I would recommend the first option before the second.

    Allowing you to do:

    var predicate = PredicateBuilder.True();
    
    if(!string.IsNullOrEmpty(name))
        predicate = predicate.And(p => p.name == name);
    
    
    ...
    
    var myResults = Context.MyLinTypeQueryTable.Where(predicate);
    

    And more.

提交回复
热议问题