Get row index in datatable from a certain column

痴心易碎 提交于 2021-02-18 09:54:51

问题


| 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.


回答1:


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



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



回答3:


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



回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/13952660/get-row-index-in-datatable-from-a-certain-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!