Home > Net >  Best way to find model with property in array
Best way to find model with property in array

Time:04-04

I have an array which i get from db:

public class Employee
{
    public long Id { get; set; }       
    public string EmployeeId { get; set; }          
}

I get from db by simple query:

Employee[] employee = 
await this.unitOfWork.Employees
.Where(x => x.Id = id && (x.EmployeeId == employeeId && x.EmployeeId == "-1"))
.ToArrayAsync(cancellationToken);

for this x.Id a can have many model with EmployeeId. for example:

Employee[] employees = new Employee[]
{
    new()
    {
        Id = 1,
        EmployeeId = "5ee62bf9-a248-49e0-b828-c83eb4128ba1"
    },
    new()
    {
        Id = 1,
        EmployeeId = "f361fa2b-1749-4905-9f2f-0a167d66befc"
    },
    new()
    {
        Id = 1,
        EmployeeId = "-1"
    }
};

EmployeeId = "-1" its for default user

and than I need check if I find input employeeId then I need return this model or I need return model with default EmployeeId = "-1".

if (employee.Length > 0)
{
    int index = Array.FindIndex(employee, x => x.EmployeeId.Equals(employeeId));
    if (index > 0)
    {
        return employee[index]);
    }
                
    index = Array.FindIndex(employee, x => x.EmployeeId == "-1");
    if (index > 0)
    {
        return return employee[index]);
    }
}

what is the best way to do it? this code works, but i see that there are a lot of if conditions

CodePudding user response:

As you mentioned your code is working and need to do something better.

You can change all this:

if (employee.Length > 0)
{
    int index = Array.FindIndex(employee, x => x.EmployeeId.Equals(employeeId));
    if (index > 0)
    {
        return employee[index]);
    }
                
    index = Array.FindIndex(employee, x => x.EmployeeId == "-1");
    if (index > 0)
    {
        return return employee[index]);
    }
}

to something like this:

return employee.FirstOrDefault(e => e.EmployeeId == employeeId) ??
                     employee.FirstOrDefault(e => e.EmployeeId == "-1");

CodePudding user response:

If the employeeId is always -1 for default then no need to get it from database(in my opinion).

BTW the solution is to use FirstOrDefault with default value like this:

Employee[] employee = 
await this.unitOfWork.Employees
.Where(x => x.Id = id && (x.EmployeeId == employeeId || x.EmployeeId==-1))
.ToArrayAsync(cancellationToken);

return employee.FirstOrDefault(x=>x?.EmployeeId==employeeId , employee.FirstOrDefault());

//for pre .net 6 use this
return employee.FirstOrDefault(x=>x?.EmployeeId==employeeId) ?? employee.FirstOrDefault();
  • Related