开发者

Advanced database search using linq-to-sql help

开发者 https://www.devze.com 2023-01-25 14:27 出处:网络
I have a database table that contains \"commands\" and \"states\". Each command can have several states, and the user is able to configure this when search. For example, the command could be \"Run\" a

I have a database table that contains "commands" and "states". Each command can have several states, and the user is able to configure this when search. For example, the command could be "Run" and it could have two states: "Fast" and "Slow".

I want to search my table for all commands called "Run" with "Fast" or "Slow". This is pretty simple to do:

var results = from t in table
              where t.Command == "Run" &&
              (t.State == "Fast" || t.State == "Slow")
              return t;

However the user could also search co开发者_JS百科mmand "Walk" with state "Fast", and so the query would look like:

    var results = from t in table
                  where (t.Command == "Run" &&
                        (t.State == "Fast" || t.State == "Slow")) ||
                  (t.Command == "Walk" &&
                   t.State == "Fast")
                  return t;

There is a potential for as many searches like this, and I'm wondering how to combine them in a loop of sorts.

I can't do this:

foreach(var command in commands)
{
    foreach(var state in command.states)
    {
        results = from t in table
                  where t.Command == command.Command &&
                  t.State == state;
    }
}

because once it searches for "Run", "Walk" would be left out of results so asking for "Walk" would result in NO results at all.

Does anyone know of a good way to do this?


Use Joe Albahari's PredicateBuilder to build a predicate:

var predicate = PredicateBuilder.False<Entry>();
foreach(var command in commands)
{
    foreach(var state in command.states)
    {
        predicate = predicate.Or(p => p.Command == command.Command && p.State == state);
    }
}
var query = table.Where(predicate);

Or a more LINQ-heavy version:

var commandStates = from c in commands
                    from s in c.states
                    select new {c.Command, State = s};
var predicate = commandStates.Aggregate(
    PredicateBuilder.False<Entry>(),
    (pred, e) => pred.Or(p => p.Command == e.Command && p.State == e.state));
var query = table.Where(predicate);
0

精彩评论

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