Dynamic query in LINQ

后端 未结 5 698
甜味超标
甜味超标 2021-02-11 06:47

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:45

    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.

提交回复
热议问题