How to add rows from data table to list using C#?

Ahmed Salah Abed Elaziz 390 Reputation points
2023-02-04T23:16:28.2833333+00:00

I work on c# console application

I need to add data table rows to list using c#

so How to do that please ?

so How to add rows from data table to object list ?

meaning

How to store

row[0].ToString()

on list .

What I have tried:

C#

string query = @"SELECT WFAN8 FROM CRPDTA.F600004A WHERE (LTRIM(WFROLE) = 'PLNG')";
 DataTable dt = JdeDataAccess.GetRecords(query);
 if (dt.Rows.Count > 0)
 foreach (DataRow row in dt.Rows)
row[0].ToString();
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,097 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Reza Aghaei 4,936 Reputation points MVP
    2023-02-04T23:39:03.8166667+00:00

    DataTable has a collection of Rows, and you can get each rows by index, or using the enumerator (in a foreach loop), for example:

    for(var i=0; i<dt.Rows.Count; i++)
    {
        var row = dt.Rows[i];
    }
    

    or

    foreach(DataRow row in dt.Rows)
    {
    }
    

    You can get column values using either of the following options:

    • Column Index: For example dt.Rows[0][0]
    • Column Name: For example dt.Rows[0]["FirstName"]
    • Field<> method: For example dt.Field<string>(0), or dt.Field<string>("FirstName")

    That said, you can show all the rows and their values like this:

    using System.Data;
    using System.Runtime.InteropServices;
    
    namespace SampleConsoleApp
    {
        internal static class Program
        {
    
            [STAThread]
            static unsafe void Main()
            {
                var dt = new DataTable();
                dt.Columns.Add("Code", typeof(int));
                dt.Columns.Add("Name", typeof(string));
                dt.Rows.Add(1, "One");
                dt.Rows.Add(2, "Two");
                dt.Rows.Add(3, "Three");
    
                foreach (DataRow row in dt.Rows)
                {
                    Console.WriteLine($"Code:{row[0]}, Name:{row[1]}");
                }
            }
        }
    }
    

    Or the following option, is a little different, returns a List<string> where each row is string representation of the row:

    var list = dt.AsEnumerable().Select(
        row => string.Join(",", row.ItemArray.Select(value => $"{value}")))
        .ToList();