find the row number of a datatable column containing specific value C#

Viewed 3407

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

2 Answers

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

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.

Related