user348173
user348173

Reputation: 9278

conditional check in predicate LINQ

I have a class which returns a predicate:

public class UserPredicateBuilder 
    {
        public Guid Id{ get; set; }
        public IEnumerable<Role> Roles{ get; set; }
        public UserType UserType{ get; set; }


        protected override Expression<Func<User, bool>> Predicate
        {
            get
            {
                return l => l.UserType == UserType
                            && l.Id== Id
                            && Roles.Contains(l.Role);
            }
        }
    }

public enum UserType
{
   None,
   Admin,
   User,
   Guest
}

public enum Role
{
   None,
   Create,
   Delete,
   Update
}

Now, the Predicate property checks all of the fields. I want to check:
- Id if it's not equal to Guid.Empty;
- UserType if it's not equal to None;
- Roles in the same way, iterate via collection, select only not None elements and check it;

In the traditional way I can do this like that:

public class SomeClass
{
   public Guid Id { get; set; }
   public IEnumerable<Role> Roles{ get; set; }
   public UserType UserType{ get; set; }

   public IList<User> GetUsers(some args)
   {
      IQueryable<User> query = ...;
      if(user.Id != Guid.Empty)
         query = query.Where(u=>u.Id == Id);

      if(user.UserType != UserType.None)
         query = query.Where(u=>u.UserType == UserType)

      ...

      return query.ToList();
    }
}

How to do this in my scenario? I found the PredicateBuilder class, can you show me how to solve my problem with this class?

Upvotes: 1

Views: 1024

Answers (1)

decPL
decPL

Reputation: 5402

You could do something like this (I'm not sure if I read your requirements correctly, but hopefully this is a valid starting point):

return l => (UserType == UserType.None || l.UserType == UserType)
          && (Id == Guid.Empty || l.Id == Id)
          && (!Roles.Any() || Roles.Where(r => r != Role.None).Contains(l.Role));

Upvotes: 1

Related Questions