How to filter IEnumerable based on an entity input parameter

前端 未结 3 1201
后悔当初
后悔当初 2021-01-01 01:31

I\'m using now Entity framework- but it\'s a problem \"shared\" between all ORM\'s and even IEnumerable.

Let\'s say I have a method in MVC looks like this:



        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-01 01:56

    Your hard coded method is the best method generally.

    However you can try to make your life a little easier by writing an appropriate extension method to help keep the code clean.

    Try this for example:

    public static class QueryableEx
    {
        public static IQueryable Where(
            this IQueryable @this,
            bool condition,
            Expression> @where)
        {
            return condition ? @this.Where(@where) : @this;
        }
    }
    

    Now you could write this code:

    [HttpPost]
    public ActionResult Foo(FooModel model)
    {
        using (var context = new Context())
        {
            var data = context.Foo
                .Where(model.Date != null, x => x.Date == model.Date)
                .Where(model.Name != null, x => x.Name == model.Name)
                .Where(model.ItemCode != null, x => x.ItemCode == model.ItemCode)
                .ToList();
            return View(data);
        }
    }
    

    (Please don't forget to dispose of your context or use using to do it for you.)

提交回复
热议问题