R
R
Roman Koff2015-10-23 15:06:56
C++ / C#
Roman Koff, 2015-10-23 15:06:56

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;
  ...

Not very strong in lambda syntax, but I suppose it could be more elegant...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Makarov, 2015-10-23
@Zarinov

Expression<Func<Catalog, bool>> filter = x => (userId==null || x.UserPtr == userId) && x.IsPublished;

A
Artyom, 2015-10-23
@artem_b89

There is a very good example that once made me look in the direction of expressions. m.habrahabr.ru/post/83169
Everything you need can be found there. And then msdn, since there is little information on this topic.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question