Search code examples
c#datatabledatacolumn

How to retrieve an entire column from a data table using it's column name


I have a data table that looks like this

|id | foo | bar |
| 0 | 321 | 33  |
| 1 | 100 |  4  |
| 2 | 355 | 23  |

I want to retrive an entire column using the column name as an argument

Something like

GetColumn(dataTable, "foo")

That would return

| foo | 
| 321 | 
| 100 | 
| 355 |

Is there something that does that?


Solution

  • Try following linq :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    
    namespace ConsoleApplication108
    {
        class Program
        {
    
            static void Main(string[] args)
            {
                DataTable dt = new DataTable();
    
                dt.Columns.Add("id", typeof(int));
                dt.Columns.Add("foo", typeof(int));
                dt.Columns.Add("bar", typeof(int));
    
                dt.Rows.Add(new object[] { 0 , 321 , 33  });
                dt.Rows.Add(new object[] { 1 , 100 , 4  });
                dt.Rows.Add(new object[] { 2 , 355 , 23  });
    
                List<int> results = dt.AsEnumerable().Select(x => x.Field<int>("foo")).ToList();
    
            }
        }
    }