简体   繁体   中英

How to Create generic method to return multiple list in c#

i have create a generic method that's return a single list. but i need to pass multiple list and it will return multiple list result set in mvc using entity framework.

public void ExecuteList<T>(out List<T> obj, string sql, params object[] parameters) where T : class
    {
        using (var db = _context)
        {
            var cmd = db.Database.Connection.CreateCommand();
            cmd.CommandText = sql;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddRange(parameters);
            try
            {
                db.Database.Connection.Open();
                using (var reder = cmd.ExecuteReader())
                {
                    obj = ((IObjectContextAdapter)db).ObjectContext.Translate<T>(reder).ToList();

                }
            }
            finally
            {
                db.Database.Connection.Close();
                cmd.Dispose();
            }
        }
    }

when i call this method in my controller it will give me a single list.

   public ActionResult Index()
    { 
        List<SqlParameter> parameterList = new List<SqlParameter>();
        parameterList.Add(new SqlParameter("@pageNo", 1));
        parameterList.Add(new SqlParameter("@pageSize", 5));            
        SqlParameter[] parameters = parameterList.ToArray();
        List<PostModel> PostModel = new List<PostModel>();           
        Uow.ExecuteList<PostModel>(out PostModel, "[dbo].[sp_getdata]", parameters);  
        return View();
    }

but i need to pass multiple list and it will give me multiple list result.

           List<SqlParameter> parameterList = new List<SqlParameter>();
        parameterList.Add(new SqlParameter("@pageNo", 1));
        parameterList.Add(new SqlParameter("@pageSize", 5)); 
        SqlParameter[] parameters = parameterList.ToArray();
        List<PostModel> PostModel = new List<PostModel>();
        List<Tag> Tag = new List<Tag>();
        Uow.ExecuteList<PostModel,Tag>(out PostModel, out Tag, "[dbo].[sp_Getdata]", parameters);  

please help me how to complete above requirement.

You can use value tuple to do it.

 (ReturnType1 returnName1, ReturnType2 returnName2) Foo<T>(argument...)

For example

(T postModel, U tag) ExecuteList<T, U>(argument...)
{
      // the code
      return (postModel, tag);
}

The generic method can use some type just as the code using <T, U> and the T and U are two types.

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