从DataTable获取特定的列标题名称

时间:2017-12-26 14:44:30

标签: c# linq datatable

我需要根据值获取特定的列标题名称。

例如:我使用以下查询获取列标题列表,它工作正常,除此之外,我可以获得具有特定名称的列名,例如Department

LINQ

string[] columnNames = dt.Columns.Cast<DataColumn>()
                         .Select(x => x.ColumnName)
                         .ToArray();

如何在此查询中添加包含或存在以获取特定列。

4 个答案:

答案 0 :(得分:2)

只需添加一个过滤器,如下所示:

string[] columnNames = dt.Columns.Cast<DataColumn>()
                             .Select(x => x.ColumnName)
                             .Where(x => x == "Department")
                             .ToArray();

答案 1 :(得分:1)

您可以选择然后过滤结果:

.Select(x => x.ColumnName).Where(c => c == "Department")

或者先过滤,然后选择:

.Where(x => x.ColumnName == "Department").Select(c => c.ColumnName)

答案 2 :(得分:1)

Columns属性的类型为DataColumnCollection,它有一个索引器public DataColumn this[string name]可以按名称获取DataColumn:

DataColumn dc = dt.Columns["Department"];

按名称获取多个列,使用Select()和索引器:

List<string> names = new List<string> { "Department", "Something" };
DataColumn[] columns = names.Select(name => dt.Columns[name]).ToArray();

答案 3 :(得分:1)

List<string> containsKeys = new List<string>();
containsKeys.Add("SomeWildCard");

DataTable dt = new DataTable();
string[] columnNames = dt.Columns.Cast<DataColumn>()
                             .Select(x => x.ColumnName)
                             .ToArray().Where(t => containsKeys.Contains(t)).ToArray();