开发者

Loop over parameters to generate LINQ at runtime

public class Command
{
    public int CommandId { get; set开发者_运维知识库; }
    public string Title { get; set; }
    public virtual ICollection<CommandPart> CommandParts { get; set; }
}

public class CommandPart
{
    public int CommandPartID { get; set; }
    public string part { get; set; }
    public virtual ICollection<Command> command { get; set; }
}

public ViewResult Filter(string myString)
{
    var foo = myString.Split(Convert.ToChar("+"));
    var a = foo[0];
    var b = foo[1];

    var query =
    db.Commands.Where(
        c =>
        c.CommandParts.Any(p => p.part == a) 
        && (c.CommandParts.Any(p2 => p2.part == b))).ToList();

    return View(query.ToList());
}

The query above works as expected when there are exactly two items in foo. I would like to be able to loop over foo to create the query. Here is my attempt, but it is not working:

        var foo = myString.Split(Convert.ToChar("+"));
        IQueryable<Command> query = db.Commands;

        foreach (var keyword in foo)
        {
            query = query.Where(c => c.CommandParts.Any(p => p.part == keyword));
        }

This is an ASP.NET MVC3 project using Entity Framework. How can I write the query so that it is generated at runtime?


Look at PredicateBuilder. It's a small helper class that encapsulates some LINQ Expressions that allow you to dynamically build up your Where predicate clause. You can AND and OR clauses together, and nest them pretty deep.

So you could do something like this (pseudo-code):

var predicate = PredicateBuilder.True<Command>(); //use True for ANDs
foreach(var keyword in foo) {
  predicate = predicate.And(c => c.CommandParts.Any(p => p.part==keyword));
}
var results = db.Commands.Where(predicate);

I missed that you're using EF, so you'll need to download LINQKit (a NuGet that you can download, too), and use its 'AsExandable' extension. See the PredicateBuilder page about this (about half-way down).

Hope this helps!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜