从特定列获取数据表中的行索引 [英] 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;
}
是否有任何方法可以简化此代码以获取提供的列的特定行的索引?在这种情况下,索引将为 0
,因为我要遍历第一列,直到找到"A"为止.感觉应该对此有一个linq解决方案,但我无法弄清楚.
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.
推荐答案
如果使用 List< T> .FindIndex
确定给定谓词的索引:
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
这篇关于从特定列获取数据表中的行索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文