简体   繁体   中英

How to get value of second column, that is the same name with another column in dataTable by C#

I have a dataTable get from calling a stored procedure in SQL Server, it has 2 columns with the same name: NAME_PROJECT

Example: result from this query:

SELECT
    NAME_PROJECT,
    DATE,
    ...
    NAME_PROJECT,
    ...
FROM
    TABLE_A

This is my code in C#, it always get value of the first column:

dataTable.Rows[i].Field<string>("NAME_PROJECT")

Because some reason, I can not change KEY "NAME_PROJECT" from SQL to avoid the same name column.

How to get value of the second NAME_PROJECT column in this problem?

Thanks!

Field is overloaded to accept column index as well, you could use pass an index in this case.

dataTable.Rows[i].Field<string>(2);

Update:

Since you want to take second column when there are duplicate column names, I would suggest doing this.

var column = dataTable.Columns
                      .OfType<DataColumn>()
                      .LastOrDefault(x=> x.ColumnName == "columnname");

if(column != null)
{
     dataTable.Rows[i].Field<string>(column); 
}

您可以为查询中的重复列名之一加别名,以使存储过程返回的结果集不会出现重复列名的问题

一种解决方案是使用索引选择所需的列。

string Second_Name_Porject = dataTable.Rows[i].ItemArray[2];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM