weknowgp
weknowgp

Reputation: 49

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

Upvotes: 1

Views: 3290

Answers (1)

johnnyRose
johnnyRose

Reputation: 7490

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.

Upvotes: 1

Related Questions