user8241949
user8241949

Reputation:

c# datatable/datagrid to List<T>

I'm pulling data from excel into a datatable and then to a datagrid. The data is in a format similar to;

"Time","Dist","speed","susp","rpm"
"0.000","0","235","29","13550"
"0.005","1","240","28.5","13560"
"0.010","2","245","28","13570"
"0.015","3","250","27.5","13580"
"0.020","4","255","27","13590"
"0.025","5","260","26.5","13600"
"0.030","6","265","26","13610"

However, the number of columns I have and the names of them are unknown in advance and will change from dataset to dataset.

The data is pulled in on a button click event (WPF);

    private void databtn_Click(object sender, RoutedEventArgs e)
    {
        {
            OpenFileDialog openfile = new OpenFileDialog();
            openfile.DefaultExt = ".xlsx";
            openfile.Filter = "(.xlsx)|*.xlsx";

            var browsefile = openfile.ShowDialog();

            if (browsefile == true)
            {
                datafilepath.Text = openfile.FileName;

                ExcelEngine excelEngine = new ExcelEngine();

                IApplication application = excelEngine.Excel;

                application.DefaultVersion = ExcelVersion.Excel2013;

                IWorkbook workbook = application.Workbooks.Open(datafilepath.Text);

                IWorksheet worksheet = workbook.Worksheets[0];

                DataTable dt = worksheet.ExportDataTable(worksheet.UsedRange, ExcelExportDataTableOptions.ColumnNames);

                DG.ItemsSource = dt.DefaultView;
            }
        }
    }

How can i put each of these columns into individual lists of values, where the name of the list is given by the column header?

I will then use those to plot x,y charts; (time,rpm) or (distance,rpm) - I can do this, but i can't seem to iterate through the values in a specified column in the datatable or datagrid.

I am new to c# and programming in general, sorry if this is elementary and thank you in advance for any help you can give.

Upvotes: 0

Views: 109

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460288

You can store the lists in a Dictionary<string, List<object>>:

Dictionary<string, List<object>> dict = dt.Columns.Cast<DataColumn>()
    .ToDictionary(c => c.ColumnName, c => dt.AsEnumerable().Select(r => r[c]).ToList());

This is a LINQ query, so you have to add using System.Linq.

Output:

foreach (var kv in dict)
   Console.WriteLine($"Column: {kv.Key}, All values: {String.Join(",", kv.Value)}");

Upvotes: 3

Related Questions