ceds
ceds

Reputation: 2185

Use LINQ to get datatable row numbers meeting certain conditions

How can I get an array of datatable row numbers which meet a certain criteria? For example I have a datatable with a column "DateTime". I want to retrieve the row numbers of the datatable where "DateTime" equals the variable startTime.

I know how to retrieve the actual row, but not the number of the row in the datatable.

Any help will be appreciated :)

Upvotes: 2

Views: 19839

Answers (3)

Anthony Pegram
Anthony Pegram

Reputation: 126932

If I am reading the question right, using the overload of Select that allows a second input for the index may work for you. Something like

var indices = 
    table.AsEnumerable()
         .Select((row, index) => new { row, index })
         .Where(item => item.row.Field<DateTime?>("DateTime") == startTime)
         .Select(item => item.index)
         .ToArray();

If that date matches on the first, third, and sixth rows, the array will contain indices 0, 2, and 5. You can, of course, add 1 to each index in the query if you would like row numbers to start at 1. (ex: .Select(item => item.index + 1))

Upvotes: 7

Tim Schmelter
Tim Schmelter

Reputation: 460208

int count = tblData.AsEnumerable()
    .Count(row => row.Field<DateTime>("DateTime").Equals(startTime));

or as query:

int count = (from row in tblData.AsEnumerable()
             where row.Field<DateTime>("DateTime").Equals(startTime)
             select row).Count();

Upvotes: 7

Mathieu
Mathieu

Reputation: 4520

This is not possible. Note that with SQL (I assume you use SQL), the row order returned is not guaranteed. Your rows are ordered physically according to the primary key. So if you want a reliable row identifier, you must use your primary key number/id.

Upvotes: -1

Related Questions