| 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.
Select("Column1 = 'this'"); Once you get the row(s), you can find its index using DataTable. Rows. IndexOf() method.
The rowIndex property returns the position of a row in the rows collection of a table.
For each row that is generated for display, the fnRowCallback() function is called. It is passed the row node which can then be modified.
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
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With