Click here to Skip to main content
15,917,176 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I work on c# I face issue I can't return count of rows with list of rows returned .
so I need to return list of rows and this id done

remaining to return count with it

so How to do it please ?

What I have tried:

Employee Model
public class EmpModel
{
    public int EmployeeId { get; set; }
    public string EmployeeName { get; set; }
    public int EmployeeStatus { get; set; }
}

public List<EmpModel> GetAllEmployees()
{
    connection();
    List<EmpModel> EmpList = new List<EmpModel>();

    SqlCommand com = new SqlCommand("GetEmployees", con);
    com.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter da = new SqlDataAdapter(com);
    DataTable dt = new DataTable();

    con.Open();
    da.Fill(dt);
    con.Close();   
    foreach (DataRow dr in dt.Rows)
    {

        EmpList.Add(
            new EmpModel
            {
                EmployeeId = Convert.ToInt32(dr["EmployeeId"]),
                EmployeeName = Convert.ToString(dr["EmployeeName"]),
                EmployeeStatus = Convert.ToInt32(dr["EmployeeStatus"])
            }
            );
    }
Posted
Updated 6-Feb-23 12:42pm
Comments
PIEBALDconsult 6-Feb-23 17:08pm    
Uh, the List has a Count property, yes?
ahmed_sa 6-Feb-23 17:20pm    
ok but if i need to return count with rows
are this possible if yes how
Graeme_Grant 6-Feb-23 18:26pm    
EmpList.Count is the total number of rows as @PIEBALDconsult indicated
PIEBALDconsult 6-Feb-23 21:46pm    
Look at it this way. You buy a book, the book contains a table of contents. You want to return "the book and its table of contents" -- all you have to do is return the book _because_it_contains_the_table_of_contents_.
It's the same thing, the List contains the Count of item/rows.

1 solution

The way you seem to be thinking, no, you can only return ONE THING, the collection OR the count, not both.

But, in your code, you're filling a DataTable with a bunch of rows from the database. Then you're converting the data to an EmpModel object and adding that to a List<empmode>. Once you have that list complete, YOU ALREDY HAVE THE COUNT OF ROWS! It's in the EmpList.Count property.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900