简体   繁体   English

如何计算var中的记录数

[英]How to count number of records in a var

I have the below code which is returning me a model from database.我有以下代码,它从数据库返回 model。 I want to know how many records are written.我想知道写了多少条记录。 I am trying to use model.count or model.lenght but its not working.我正在尝试使用model.countmodel.lenght但它不起作用。

var model = await _repository.GetEmployees(name);

GetEmployees method is defined as follows: GetEmployees 方法定义如下:

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.我需要知道记录的数量。

add System.Linq to your usings.将 System.Linq 添加到您的使用中。 It will give an extension method to all IEnumerables called Count()它将为所有 IEnumerables 提供一个扩展方法,称为 Count()

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.既然您知道它是List<>您的方法应该返回该类型。 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.否则,您只是在自欺欺人,其直接后果是,您的程序将充斥着效率低下的 Linq、查询已经存在的数据,或者对已经实现的事物进行大量ToList调用。

So either make it a list and subsequently use the Count property.因此,要么将其设为列表,然后使用Count属性。

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):或者将其保留为IEnumerable ,因为您不想为调用者实现它(也许有充分的理由):

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.例如,只有在调用者实际尝试枚举它并且谁知道_context是否仍然存在时,才会进行数据库调用。

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:如果你真的只需要计数,你应该从数据库中查询,而不是向你的应用程序发送数百名员工,当一个简单的“359”或类似的 integer 就足够了:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM