Answer the question
In order to leave comments, you need to log in
How to simplify code with lambda operations?
Depending on a certain condition, you need to compose a lambda expression. How to make it simpler so that the code is more elegant.
In the example, depending on the presence of a value in UserId, different labda expressions are used for the request filter:
public CatalogModel GetListCatalogModels(int? userId)
{
Expression<Func<Catalog, bool>> filter1 = x => x.IsPublished;
Expression<Func<Catalog, bool>> filter2 = x => x.UserPtr == userId && x.IsPublished;
Expression<Func<Catalog, bool>> filter;
if (userId == null)
filter = filter1;
else
filter = filter2;
...
Answer the question
In order to leave comments, you need to log in
Expression<Func<Catalog, bool>> filter = x => (userId==null || x.UserPtr == userId) && x.IsPublished;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question