Reuse of a LINQ query

前端 未结 4 531
梦谈多话
梦谈多话 2020-12-14 06:06

This is not about the reuse of a result but more the statement itself. Nor is it about an error when using var as mentioned in: LINQ to SQL: Reuse lambda expression

4条回答
  •  失恋的感觉
    2020-12-14 06:48

    I wrote a library to address exactly this concern, it's called CLinq and you can find an implementation for the EntityFramework here: https://www.nuget.org/packages/CLinq.EntityFramework

    It allows to create query snippets and use them everywhere you in a linq query. Following the example of Hamid, create the following expression:

    System.Linq.Expressions.Expression> selector = x => x.Contains("");

    You can now use this query everywhere in your linq queries like this:

    query.AsComposable().Where(o => selector.Pass(o));

    Additionally to this simple example you're also able to combine your query snippets:

    query.AsComposable().Where(o => selector.Pass(o) || anotherSelector.Pass(o));

    or even merge them together:

    query.AsComposable().Where(o => anotherSelector.Pass(selector.Pass(o)));

    There's some more features, but I think it's really helpful, so check it out :)

提交回复
热议问题