3

I have a datatable in C# with a column called Point that contains various integer values. How do I find the row number of the first row that is equal to a specific value. E.g. Maybe I want to find the first time that the number 52 appears in the Point Column and it appears first at row 10. How do I find the value 10?

Note that I want to find the row number and not the value of another column at this position, hence why this question is different to: Find row in datatable with specific id

Siavash
  • 2,813
  • 4
  • 29
  • 42
Daniel Wyatt
  • 960
  • 1
  • 10
  • 29
  • Possible duplicate of [Find row in datatable with specific id](https://stackoverflow.com/questions/20638351/find-row-in-datatable-with-specific-id) – ArunPratap Oct 31 '18 at 11:42
  • Don't think so. That article doesn't tell you how to get the row number. – Daniel Wyatt Oct 31 '18 at 11:46
  • Possible duplicate of [How to get the row number from a datatable?](https://stackoverflow.com/questions/4502920/how-to-get-the-row-number-from-a-datatable) – Peter B Oct 31 '18 at 11:52
  • @ArunPratap Assuming that default id schema is used, and no rows have ever been deleted, then yes, the id will return the row number. – addohm Oct 31 '18 at 11:56

2 Answers2

3

A for loop is probably the simplest way. This answer returns the index of the row (row number) in the DataTable which matches a specific value.

int firstRow = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
    var row = dt.Rows[i];
    int point = Convert.ToInt32(row["Point"].ToString());
    if (point == 52)
    {
        // i is the first row matching your condition
        firstRow = i;
        break;
    }
}
haldo
  • 14,512
  • 5
  • 46
  • 52
0

The following may work for you:

DataTable table = new DataTable("SomeData");
table.Columns.Add("Point", typeof(int));
table.Rows.Add(5);
table.Rows.Add(7);
table.Rows.Add(52);
table.Rows.Add(2);
table.Rows.Add(1);
table.Rows.Add(4);
table.Rows.Add(9);

var row = table.AsEnumerable().Select((r, i) => new { Row = r, Index = i }).Where(x => (int)x.Row["Point"] == 52).FirstOrDefault();
int rowNumber = 0;
if (row != null)
    rowNumber = row.Index + 1;

Note that in this example I give the row number, not the index that starts from zero.

Zhavat
  • 214
  • 1
  • 6