Home > Software design >  How to count number of records in a var
How to count number of records in a var

Time:08-16

I have the below code which is returning me a model from database. I want to know how many records are written. I am trying to use model.count or model.lenght but its not working.

var model = await _repository.GetEmployees(name);

GetEmployees method is defined as follows:

public async Task<IEnumerable<Employee>> GetEmployees(string name)
{
    return await _dbContext.Employee
        .Where(c => c.EmpName == name).ToListAsync();
}

I need to know the count of records.

CodePudding user response:

add System.Linq to your usings. It will give an extension method to all IEnumerables called Count()

CodePudding user response:

public async Task<IEnumerable<Employee>> GetEmployees(string name)
{
    return await _dbContext.Employee
        .Where(c => c.EmpName == name).ToListAsync();
}

Since you know it is a List<> your method should return that type. Otherwise you are just lying to yourself and as a direct consequence, your program will be littered with inefficient Linq, quering already existing data, or lots and lots of ToList calls on things that are already materialized.

So either make it a list and subsequently use the Count property.

public async Task<List<Employee>> GetEmployees(string name)
{
    return await _dbContext.Employee
        .Where(c => c.EmpName == name).ToListAsync();
}

Or leave it as an IEnumerable because you want to not materialize it for your caller (maybe for good reason):

public async IEnumerable<Employee> GetEmployees(string name)
{
    return await _dbContext.Employee.Where(c => c.EmpName == name);
}

However, this is tricky for many reasons. For example the database call will only be made once the caller actually tries to enumerate this and who knows whether _context is still alive then.

And if you really only need the count, you should query that from the database instead of sending over hundreds of employees to your application, when a simple integer of "359" or similar would have been enough:

public async Task<int> GetNumberOfEmployees(string name)
{
    return await _dbContext.Employee
        .CountAsync(c => c.EmpName == name);
}
  • Related