AC25
AC25

Reputation: 423

Linq get the column Name of a datatable by using the column Index

I am trying to be able to find one of the Column name of a datatable by using the Column index with Linq. Example:

  int colindex = 2;

  Datatable: PersonInfo
  ID Name Address City State Country Zip 
  1  xx    11-23    LA  CA    USA    9123

  PersonInfo.AsEnumerable().Select(x => x.field<int>(Colindex).ColumnName);

  returns Address

Upvotes: 0

Views: 4399

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

Why are you trying to use LINQ to do that? It's as easy as:

var columnName = PersonInfo.Columns[colindex].ColumnName;

You code does not work, because Field<T> extension method returns T, so Field<int> returns int and there is no way to get column name from that int value.

If you really have to use LINQ, you should query DataTable.Columns property, not the rows:

var columnName = PersonInfo.Columns.Cast<DataColumn>().ElementAt(colindex).ColumnName;

Upvotes: 7

Related Questions