开发者

How can I separate the condition within a LINQ to SQL query?

I am using ASP.NET with C# and I need to make the condition of the query dynamic, Example:

Database:

 Name       Sex
 --------------
 John Doe    M
 Jane Doe    F

Now I want to allow a search on the data set but if the user selects to search by name OR sex only the query will allow a search on the name or sex columns. However if the user selects to search by both name and sex them the query will allow a search by name AND sex column. My quest开发者_Python百科ion is can I separate the query using if statements to account for the dynamic nature of the search? Thank you.


You can do:

var q = ...;

if(sex != null) {
    q = q.Where(r => r.Sex == sex);
}
if(name != null) {
    q = q.Where(r => r.Name == name);
}

This will filter by sex and/or name depending on what is passed in.

q = q.Where(r => r.Sex == sex).Where(r => r.Name == name);

is the same as

q = q.Where(r => r.Sex == sex && r.Name == name);


Steven is right, that is one good and easy way to do it and would work great for your needs. If you ever get into a situation where you may have several conditional statements, it would be wise to look into dynamic linq. Dynamic linq would allow you to write a query such as:

    DatabaseDataContext db = new DatabaseDataContext();

    string WhereClause = string.Empty;

    if (!string.IsNullOrEmpty(Name))
        WhereClause += "Name.ToLower().Contains(\"" + Name.ToLower() + "\") AND ";

    if (!string.IsNullOrEmpty(State))
        WhereClause += "City.State.Name.ToLower().Contains(\"" + State.ToLower() + "\") AND ";

    if (!string.IsNullOrEmpty(County))
        WhereClause += "City.County.Name.ToLower().Contains(\"" + County.ToLower() + "\") AND ";

    if (!string.IsNullOrEmpty(City))
        WhereClause += "City.Name.ToLower().Contains(\"" + City.ToLower() + "\") AND ";


    if (WhereClause.EndsWith(" AND "))
        WhereClause = WhereClause.Remove(WhereClause.Length - 5);

    var query = db.Communities
                .Where(WhereClause)
                .OrderBy("Name");

You can get the dynamic linq class here http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Good Luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜