简体   繁体   中英

Return different types of Lists<> in Method (C#)

At the moment I have a Method for executing database calls which returns a DataTable which is then converted into a List<> . Since I am using this Method for different database calls I need to make it return any List<> . This is at the moment not possible since I get an error:

Cannot convert List<T> to List<object>

What return type should the function have if i want to return any list? eg it could be that the result list is of the type:

List<MirrorDeployments>

or:

List<ProductionDeployments>

My Function

public List<T> Execute<T>(string strSql, List<T> list)
{
    using (OracleConnection conn = new OracleConnection(cnnStr))
    {
        using (OracleCommand objCommand = new OracleCommand(strSql, conn))
        {
            objCommand.CommandType = CommandType.Text;
            DataTable dt = new DataTable();
            OracleDataAdapter adp = new OracleDataAdapter(objCommand);
            conn.Open();
            adp.Fill(dt);
            if (dt != null)
            {

                list = ConvertToList(dt, list).ToList();
            }
        }
    }
    return list;
}

Assuming that ConvertToList returns an enumerable of object :

public List<T> Execute<T>(string strSql)
{
    using (OracleConnection conn = new OracleConnection(cnnStr))
    {
        using (OracleCommand objCommand = new OracleCommand(strSql, conn))
        {
            objCommand.CommandType = CommandType.Text;
            DataTable dt = new DataTable();
            OracleDataAdapter adp = new OracleDataAdapter(objCommand);
            conn.Open();
            adp.Fill(dt);
            if (dt != null)
            {

                return ConvertToList(dt).Cast<T>().ToList();
            }
        }
    }
    return new List<T>();
}

I have removed the parameter list because seems useless.

A better option is to convert ConvertToList in a generic method ConvertToList<T> which does what its name say.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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