[c#] How to convert a column of DataTable to a List

I have a DataTable with multiple columns. I want to get a List<String> out of first column of DataTable. How can I do that?

This question is related to c# .net list datatable

The answer is


I make a sample for you , and I hope this is helpful...

    static void Main(string[] args)
    {
        var cols = new string[] { "col1", "col2", "col3", "col4", "col5" };

        DataTable table = new DataTable();
        foreach (var col in cols)
            table.Columns.Add(col);

        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });

        foreach (var col in cols)
        {
            var results = from p in table.AsEnumerable()
                          select p[col];

            Console.WriteLine("*************************");
            foreach (var result in results)
            {
                Console.WriteLine(result);
            }
        }


        Console.ReadLine();
    }

var list = dataTable.Rows.OfType<DataRow>()
    .Select(dr => dr.Field<string>(columnName)).ToList();

[Edit: Add a reference to System.Data.DataSetExtensions to your project if this does not compile]


Is this what you need?

DataTable myDataTable = new DataTable();
List<int> myList = new List<int>();
foreach (DataRow row in myDataTable.Rows)
{
    myList.Add((int)row[0]);
}

Here you go.

           DataTable defaultDataTable = defaultDataSet.Tables[0];
           var list = (from x in defaultDataTable.AsEnumerable()
                    where x.Field<string>("column1") == something
                    select x.Field<string>("column2")).ToList();

If you need the first column

           var list = (from x in defaultDataTable.AsEnumerable()
                    where x.Field<string>(1) == something
                    select x.Field<string>(1)).ToList();

Try this:

static void Main(string[] args)
{
    var dt = new DataTable
    {
        Columns = { { "Lastname",typeof(string) }, { "Firstname",typeof(string) } }
    };
    dt.Rows.Add("Lennon", "John");
    dt.Rows.Add("McCartney", "Paul");
    dt.Rows.Add("Harrison", "George");
    dt.Rows.Add("Starr", "Ringo");

    List<string> s = dt.AsEnumerable().Select(x => x[0].ToString()).ToList();

    foreach(string e in s)
        Console.WriteLine(e);

    Console.ReadLine();
}

I do just like below, after you set your column AsEnumarable you can sort, order or how you want.

 _dataTable.AsEnumerable().Select(p => p.Field<string>("ColumnName")).ToList();

1.Very Simple Code to iterate datatable and get columns in list.

2.code ==>>>

 foreach (DataColumn dataColumn in dataTable.Columns)
 {
    var list = dataTable.Rows.OfType<DataRow>()
     .Select(dataRow => dataRow.Field<string> 
       (dataColumn.ToString())).ToList();
 }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to datatable

Can't bind to 'dataSource' since it isn't a known property of 'table' How to get a specific column value from a DataTable in c# Change Row background color based on cell value DataTable How to bind DataTable to Datagrid Find row in datatable with specific id Datatable to html Table How to Edit a row in the datatable How do I use SELECT GROUP BY in DataTable.Select(Expression)? How to fill a datatable with List<T> SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column