简体   繁体   中英

Get All Row Elements of Data Table From Column LINQ c#

I have a DataTable with the Column name "Part Number" and various other columns. I want to grab all of the elements that are in the column "Part Number". This column can sometimes be in a different position so I can't just assign a particular Item Array index. I want to use LINQ to do it.

Right now, I just grab everything in the first column. However, I want to set this to grab the data according to the column heading.

var parts = from row in dataTable.AsEnumerable()
            where true != string.IsNullOrWhiteSpace((row.ItemArray[0] == DBNull.Value)
                ? string.Empty
                : row.ItemArray[0].ToString())
            select row.ItemArray[0];

You can index a DataColumnCollection by a DataColumn , like this:

// Find the DataColumn by column name
string columnName = "Part Number";
DataColumn partNumber = dataTable.Columns[columnName];

var parts = from row in dataTable.AsEnumerable()
            where !string.IsNullOrWhiteSpace(row[partNumber].ToString())
            select row[partNumber];

Let the DataTable worry about finding the index inside the ItemArray . All you have to know is the column name.

For more information, see the documentation .

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