Johan
Johan

Reputation: 35194

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.

Upvotes: 16

Views: 48342

Answers (5)

StuartLC
StuartLC

Reputation: 107267

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

Upvotes: 10

Yannick Blondeau
Yannick Blondeau

Reputation: 9621

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

Upvotes: 5

Jay Sampat
Jay Sampat

Reputation: 195

Use linq operation, but for that your target framework should be 4.5. Import system.Data.DataExtensions and apply the linq query will help you out.

Upvotes: 0

Pete
Pete

Reputation: 10871

var index = from row in dt.AsEnumerable()
            let r = row.Field<string>("1")
            where r == "A"
            select dt.Rows.IndexOf(row);

Upvotes: 3

Nabheet
Nabheet

Reputation: 1314

You could try to an identity column. However, I do not know your application so please consider the pros and the cons of adding an identity column to your datatable. Here is a reference to get you started - how to add identity column

Hope this helps.

Upvotes: 2

Related Questions