How to create a list or dictionary from a datatable?

Asked

Viewed 53 times

-1

I have 3 lines in a datatable:

DataTable dt = new DataTable();
dt.Clear();

dt.Columns.Add("PESO");
dt.Columns.Add("ALTURA");

DataRow row1 = dt.NewRow();
row1["PESO"] = "MAGRO";
row1["ALTURA"] = "BAIXO";
dt.Rows.Add(row1);

DataRow row2 = dt.NewRow();
row2["PESO"] = "MAGRO";
row2["ALTURA"] = "ALTO";
dt.Rows.Add(row2);

DataRow row3 = dt.NewRow();
row3["PESO"] = "OBESO";
row3["ALTURA"] = "BAIXO";
dt.Rows.Add(row3);

I would like to scroll through this datatable and add the results to a list so that the result looks like this:

Dictionary (where weight is the key and height is the value)

  • THIN

    • LOW
    • TALL
  • OBESE

    • LOW

I want to group the heights for each type of weight

1 answer

1


If you want to use one Dictionary to store these values you can build a Dictionary<string, list<string>>, incialize it and then popular with the distinct values, see the example below.

class Program
{
    static void Main(string[] args)
    {
        DataTable dt = new DataTable();
        dt.Clear();

        dt.Columns.Add("PESO");
        dt.Columns.Add("ALTURA");

        DataRow row1 = dt.NewRow();
        row1["PESO"] = "MAGRO";
        row1["ALTURA"] = "BAIXO";
        dt.Rows.Add(row1);

        DataRow row2 = dt.NewRow();
        row2["PESO"] = "MAGRO";
        row2["ALTURA"] = "ALTO";
        dt.Rows.Add(row2);

        DataRow row3 = dt.NewRow();
        row3["PESO"] = "OBESO";
        row3["ALTURA"] = "BAIXO";
        dt.Rows.Add(row3);

        var caracteristicas = new Dictionary<string, List<string>>();
        caracteristicas.Add("ALTO", new List<string>());
        caracteristicas.Add("BAIXO", new List<string>());


        foreach (DataRow linha in dt.Rows)
        {
            var valorPeso = linha["PESO"].ToString();
            var valorAltura = linha["ALTURA"].ToString();

            if (!caracteristicas[valorAltura].Contains(valorPeso))
                caracteristicas[valorAltura].Add(valorPeso);
        }

        //Escrevendo na tela
        foreach(var chave in caracteristicas)
        {
            Console.WriteLine($"{chave.Key}");
            foreach(var valor in chave.Value)
            {
                Console.WriteLine($"   {valor}");
            }
        }

        Console.Read();
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.