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

有没有办法简化这个代码来获取某一行的索引,并提供一列?在这种情况下,索引将为0,因为我正在遍历第一列,直到找到“A”。感觉应该有一个 linq 解决方案,但我无法弄清楚。

4

5 回答 5

10

如果您使用DataTableExtensions.AsEnumerable()方法,您将能够使用 LINQ 查询您的 DataTable。然后,您可以使用List<T>.FindIndex来确定给定谓词的索引:

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
于 2012-12-19T12:42:25.103 回答
5

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));
}
于 2012-12-19T13:09:07.773 回答
3
var index = from row in dt.AsEnumerable()
            let r = row.Field<string>("1")
            where r == "A"
            select dt.Rows.IndexOf(row);
于 2012-12-19T13:05:39.750 回答
2

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.

于 2012-12-19T12:58:18.910 回答
0

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.

于 2012-12-19T13:08:17.903 回答