0

estoy implementando consmir una api para ya no conectarme directamente a la base y necesito que el valor que retorna un metodo list sea convertido a dataset para usarlo en mi metodo pero no encuentro la forma de cambiar a que mi metodo list devuelva un dataset, solo me funciona como list el codigo del metodo list es el siguiente:

List<ApiModel> ObjCuentas = new List<ApiModel>();
    HttpClientHandler _cliente = new HttpClientHandler();
    private async Task<List<ApiModel>> CuentasClienteAsync()
    {
         ObjCuentas = new List<ApiModel>();

        try
        {   
                using (var httpClient = new HttpClient(_cliente))
                {

                    using (var response = await httpClient.GetAsync("https://localhost:7212/api/Usuarios/Cuentas/"+25408))
                    {
                        string apiResponse = await response.Content.ReadAsStringAsync();
                    ObjCuentas = JsonConvert.DeserializeObject<List<ApiModel>>(apiResponse);
                    }

                }
                return ObjCuentas;
            
        }
        catch
        {
            return ObjCuentas;
        }

    }

y necesito usarlo de esta manera:

DataSet ds = new DataSet();
        List<double> productos = new List<double>();
        List<string> labelCircular = new List<string>();
        List<double> aportaciones = new List<double>();
        List<double> dividendos = new List<double>();
        List<string> labelDividendos = new List<string>();


        try
        {
            if (Session["CorrelativoAfiliado"] != null)
            {
                ds = CuentasClienteAsync();//aca obviamente da error
                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        List<ProductosFinancieros> datos = ds.Tables[0].Rows.OfType<DataRow>().
                                    Select(x => new ProductosFinancieros()
                                    {
                                        CorrelativoAfiliado = int.Parse(x["CorrelativoAfiliado"].ToString()),
                                        CorrelativoCuenta = int.Parse(x["CorrelativoCuenta"].ToString()),
                                        Producto = x["Producto"].ToString(),
                                        NumeroCuenta = x["NumeroCuenta"].ToString(),
                                        Saldo = double.Parse(x["Saldo"].ToString()),
                                        NombreSublinea = x["NombreSublinea"].ToString(),
                                        Tipo = int.Parse(x["Tipo"].ToString())
                                    }).ToList();


                        foreach (DataRow dr in ds.Tables[1].Rows)
                        {
                            productos.Add(double.Parse(dr["Saldo"].ToString()));
                            labelCircular.Add(dr["Producto"].ToString());
                        }


                        foreach (DataRow dr in ds.Tables[2].Rows)
                        {
                            aportaciones.Add(double.Parse(dr["Saldo"].ToString()));
                        }


                        foreach (DataRow dr in ds.Tables[3].Rows)
                        {
                            dividendos.Add(double.Parse(dr["Dividendo"].ToString()));
                            labelDividendos.Add(dr["CorrelativoAnyo"].ToString());
                        }



                        ViewBag.LabelProductos = labelCircular.ToList();
                        ViewBag.Aportaciones = aportaciones.ToList();
                        ViewBag.Productos = productos.ToList();
                        ViewBag.Dividendos = dividendos.ToList();
                        ViewBag.LabelDividendos = labelDividendos.ToList();


                        ViewBag.TotalAhorros = ds.Tables[1].Compute("sum(Saldo)", "Tipo=2");
                        ViewBag.TotalAportaciones = ds.Tables[1].Compute("sum(Saldo)", "Tipo=3");
                        ViewBag.TotalPrestamos = ds.Tables[1].Compute("sum(Saldo)", "Tipo=1");                           
                        Session["IdCuenta"] = 0;
                        Session["Tipo"] = 0;
                        return View(datos);


                    }
                }
                return View("Index");
            }
            else
            {
                return RedirectToAction("Index", "Seguridad");
            }

        }
        catch
        {
            return View("Error");
        }

este es el modelo ApiModel:

namespace MyProyect.Models

{ public partial class ApiModel { [JsonProperty("Table")] public Table[] Table { get; set; }

    [JsonProperty("Table1")]
    public Table1[] Table1 { get; set; }



    [JsonProperty("Table2")]
    public Table2[] Table2 { get; set; }



    [JsonProperty("Table3")]
    public Table3[] Table3 { get; set; }



    [JsonProperty("Table4")]
    public Table4[] Table4 { get; set; }
}



public partial class Table
{
    [JsonProperty("CorrelativoAfiliado")]
    public long CorrelativoAfiliado { get; set; }



    [JsonProperty("CorrelativoCuenta")]
    public long CorrelativoCuenta { get; set; }



    [JsonProperty("Producto")]
    public string Producto { get; set; }



    [JsonProperty("NumeroCuenta")]
    public string NumeroCuenta { get; set; }



    [JsonProperty("Saldo")]
    public double Saldo { get; set; }



    [JsonProperty("NombreSublinea")]
    public string NombreSublinea { get; set; }



    [JsonProperty("Tipo")]
    public long Tipo { get; set; }



    [JsonProperty("CorrelativoSublinea")]
    public long CorrelativoSublinea { get; set; }
}



public partial class Table1
{
    [JsonProperty("Tipo")]
    public long Tipo { get; set; }



    [JsonProperty("Producto")]
    public string Producto { get; set; }



    [JsonProperty("Saldo")]
    public double Saldo { get; set; }
}



public partial class Table2
{
    [JsonProperty("Mes")]
    public long Mes { get; set; }



    [JsonProperty("Saldo")]
    public double Saldo { get; set; }
}



public partial class Table3
{
    [JsonProperty("CorrelativoAnyo")]
    public long CorrelativoAnyo { get; set; }



    [JsonProperty("Dividendo")]
    public double Dividendo { get; set; }
}



public partial class Table4
{
    [JsonProperty("Monto")]
    public double Monto { get; set; }



    [JsonProperty("Plazo")]
    public long Plazo { get; set; }



    [JsonProperty("Fecha")]
    public DateTimeOffset Fecha { get; set; }
}




internal static class Converter
{
    public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
    {
        MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
        DateParseHandling = DateParseHandling.None,
        Converters = { new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } }
    };
}    

}

el json que estoy capturando es un arreglo de tablas o matriz como gusten llamarlo

necesito que me retorne un dataset para ser mas facil su manejo en la vista de antemano gracias cualquier ayuda

2 respuestas 2

1

Puedes usar el método AsEnumerable() de la clase List<T> para convertirlo en un IEnumerable<T>, y luego utilizar el método CopyToDataTable() de la clase DataTable para convertirlo en un DataSet.

Aquí tienes un ejemplo:

List<MyObject> myList = GetMyList();
DataTable dt = myList.AsEnumerable().CopyToDataTable();
DataSet ds = new DataSet();
ds.Tables.Add(dt);
1

de echo, no es necesario usar AsEnumerable() porque el metodo CopyToDataTable() es de LinQ y es una extension de **IEnumerable<T>** y AsEnumerable() te devuelve el mismo objeto boxeado a la interfaz.

**List<T>** ya implementa **IEnumerable<T>**, entonces puedes hacer simplemente:

List<Model> list = await api.GetModels();
DataTable dt = list.CopyToDataTable();
DataSet ds = new DataSet();
ds.Tables.Add(dt);

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.