如何使用列名从数据 table 中检索整个列

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

我有一个数据 table 看起来像这样

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

我想使用列名作为参数来检索整个列

类似

GetColumn(dataTable, "foo")

那会 return

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

有什么东西可以做到这一点吗?

不完全是。但你可以这样做:

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;
}

如果您想要一些可以与其他原始类型(int、decimal、bool 等)一起使用的东西,您可能需要阅读 C# generics 并实现一个通用方法。

尝试以下 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();

        }
    }
}