Search code examples
c#linq

How to check some value and enum with linq (both parameters)?


 public enum RoleEnum
    {
        Manager = 1,
        Employee = 2
    }


public void CreateEmployee()
        {
           
            Console.WriteLine("This operation can be handle ONLY by Manager!!!");
            Console.WriteLine("Please enter your Id");
            var userManagerId = Console.ReadLine();
            CheckManagerById(userManagerId);

            if (userManagerId != null)
            {      
           
            }
                    
         }

        private  Employee CheckManagerById(string ManagerId)
        {
            
            return _employers.FirstOrDefault(x => x.Id == ManagerId);
        }

Manage functionalities can only be used by managers. (Ask for user Id and check if it is a manager). How can I check both parameters only by Id with linq?

Or how can I go on?


Solution

  • Might be too early to answer this since there's missing information, but it appears to me that you want to filter employees based on both the Id and their Role. If that's the case, then you could do something like:

    private Employee GetManager(string employeeId)
    {
        return _employees.FirstOrDefault(employee => 
            employee.Id == employeeId && 
            employee.Role == RoleEnum.Manager);
    }
    

    Then in your other method, you check the return value from this method. If it's null, then either the employee id wasn't found, or the specified employee isn't a manager:

    public void CreateEmployee()
    {
        Console.WriteLine("This operation can be handle ONLY by Manager!!!");
        Console.Write("Please enter your Id: ");
        var userId = Console.ReadLine();
    
        Employee manager = GetManager(userId);
    
        if (manager != null)
        {      
            // employee is a manager and may continue
        }
    }
    

    Alternatively, if you don't need the Employee object, but just need to know if the provided Id is a valid manager id, you could write a method that returns true if an employee with that id is a manager using the Any method, which returns true if any objects in the collection meet the criteria:

    private bool IsManager(string employeeId)
    {
        return _employees.Any(employee => 
            employee.Id == employeeId && 
            employee.Role == RoleEnum.Manager);
    }
    

    And then the calling method would look like:

    public void CreateEmployee()
    {
        Console.WriteLine("This operation can be handle ONLY by Manager!!!");
        Console.Write("Please enter your Id: ");
        var userId = Console.ReadLine();
    
        if (IsManager(userId))
        {      
            // employee is a manager and may continue
        }
    }