Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get row index in datatable from a certain column

| 1 | 2 | 3 |
+------------+
| A | B | C |
| D | E | F | 
| G | H | I |

System.Data.DataTable dt = new DataTable();

dt.Columns.Add("1");
dt.Columns.Add("2");
dt.Columns.Add("3");
dt.Rows.Add(new object[] { "A", "B", "C" });
dt.Rows.Add(new object[] { "D", "E", "F" });
dt.Rows.Add(new object[] { "G", "H", "I" });

int? index = null;

var rows = new System.Data.DataView(dt).ToTable(false, new[] {"1"}).Rows;

for (var i = 0; i < rows.Count; i++)
{
    if (rows[i].ItemArray.FirstOrDefault() as string == "A")
        index = i;
}

Is there any way to simplify this code for fetching the index of a certain row, with a column provided? In this case, index will be 0, since I'm iterating through the first column until i find "A". Feels like there should be a linq solution to this, but I can't figure it out.

like image 558
Johan Avatar asked Dec 19 '12 12:12

Johan


People also ask

How do you get the index of a row in a DataTable?

Select("Column1 = 'this'"); Once you get the row(s), you can find its index using DataTable. Rows. IndexOf() method.

What is a row index?

The rowIndex property returns the position of a row in the rows collection of a table.

What is fnRowCallback?

For each row that is generated for display, the fnRowCallback() function is called. It is passed the row node which can then be modified.


Video Answer


2 Answers

If you use the DataTableExtensions.AsEnumerable() method, you will be able to query your DataTable with LINQ. You can then use List<T>.FindIndex to determine the index of a given predicate:

int? index = new System.Data.DataView(dt).ToTable(false, new[] { "1" })
                .AsEnumerable()
                .Select(row => row.Field<string>("1")) // ie. project the col(s) needed
                .ToList()
                .FindIndex(col => col == "G"); // returns 2
like image 69
StuartLC Avatar answered Oct 27 '22 18:10

StuartLC


You should be able to use the DataTable.Select method like this:

DataRow[] foundRows;
string filter = "1 == A";
foundRows = dt.Select(filter);

foreach (DataRow dr in foundRows)
{
    Console.WriteLine("Index is " + dr.Table.Rows.IndexOf(dr));
}
like image 39
Yannick Blondeau Avatar answered Oct 27 '22 19:10

Yannick Blondeau