Miguel Manjarrez
Miguel Manjarrez

Reputation: 159

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?

Upvotes: -3

Views: 1033

Answers (2)

haku
haku

Reputation: 4505

Not exactly. But you could do something like:

private List<string> GetColumnValues(string columnName, DataTable dataTable)
{
    var colValues = new List<string>();
    foreach (DataRow row in datatable.Rows)
    {
        var value = row[columnName];
        if (value != null)
        {
            colValues.Add((string)value);
        }
    }
    return colValues;
}

If you want something that would work with other primitive types (int, decimal, bool etc), you may want to read up on C# generics and implement a generic method.

Upvotes: -1

jdweng
jdweng

Reputation: 34421

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();

        }
    }
}

Upvotes: 2

Related Questions