Dawin Dawin - 1 month ago 7
C# Question

Getting values depending of condition

I´m very new in asp.net. For some people my question disturb community.

I have a query that retrieves data from a stored procedure like this:

result = context.GetEmployeeTraining(idTraining,
idArea,
idDepartment,
type ? "(1),(2)" : "(3)").ToList();


and I have this query to retrieve a list of branches:

IGenericRepository<Employee> employee = new GenericRepository<Employee>();
var branchList = employee.GetList(x => x.BranchOfficeId == userId).ToList();


How can I filter the result of the first query to get only items that are in the
branchList
?

First I tried to get it from where condition like:

result = context.GetEmployeeTraining(idTraining,
idArea,
idDepartment,
type ? "(1),(2)" : "(3)")
.Where(x => x.BranchOfficeId == userId).ToList();


But it only get one value instead of list like my
branchList
do now

var branchList = employee.GetList(x => x.BranchOfficeId == userId).ToList();


GetEmployeeTraining
Stored Procedure:

public virtual ObjectResult<EmployeeTraining> GetEmployeeTraining(Nullable<int> idTraining,
Nullable<int> idArea,
Nullable<int> idDepartment,
string type)

Answer

One way is to use .Any:

var branchList = employee.GetList(x => x.BranchOfficeId == userId);

var result = context.GetEmployeeTraining(idTraining, 
                                         idArea, 
                                         idDepartment, 
                                         type ? "(1),(2)" : "(3)")
                    .Where(x => branchList.Any(b => b.BranchOfficeId == x.BranchOfficeId))
                    .ToList();

Another option if you chnage the query of the branchList is to use Contains:

var branchList = employee.GetList(x => x.BranchOfficeId == userId)
                         .Selet(x => x.BranchOfficeId);

var result = context.GetEmployeeTraining(idTraining, 
                                         idArea, 
                                         idDepartment, 
                                         type ? "(1),(2)" : "(3)")
                    .Where(x => branchList.Contains(x.BranchOfficeId))
                    .ToList();

I hope I got the field names correctly. Was a bit difficult to understand from the question

Comments