如何使用C#基于对象值查找行的索引?(How to find index of a row based on the object value using C#?)
我有一个datagridview,我想从中删除一个特定的行(datagridview不是数据绑定)。 要删除,我需要行的索引。 Datagridview项目都是对象。 此时,我所拥有的只是对象的id(属性)。 我想知道datagridview中行的索引,它包含id的对象,比如说2。
我该如何做到这一点? 或者是否有另一种基于对象值删除行的方法?
I have a datagridview, and I want to remove a particular row from it (datagridview is not data bound). To remove, I need the index of the row. Datagridview items are all objects. At this moment, all I have is the id (a property) of the object. I want to know the index of the row in datagridview which holds the object of id, say 2.
How do I accomplish this? Or is there another way of deleting a row based on an object's value?
最满意答案
可能有一种更清洁的方式,但使用LINQ:
private int GetIndexOfRowWithId(DataGridView dataGrid, int id) { return dataGrid.Rows.Cast<MyRowObj>().Select((row, index) => new { index, row }).Where(x => x.row.id == id).Select(x => x.index).First(); }没有LINQ:
private int GetIndexOfRowWithId(DataGridView dataGrid, int id) { for (int i = 0; i < dataGrid.Rows.Count; i += 1) { MyRowObj row = (MyRowObj)dataGrid.Rows[i].Tag; // or.DataBoundItem; if (row.id == id) { return i; } } throw new ArgumentException("No item with specified id exists in the dataGrid.", "id"); }There's probably a cleaner way, but with LINQ:
private int GetIndexOfRowWithId(DataGridView dataGrid, int id) { return dataGrid.Rows.Cast<MyRowObj>().Select((row, index) => new { index, row }).Where(x => x.row.id == id).Select(x => x.index).First(); }and without LINQ:
private int GetIndexOfRowWithId(DataGridView dataGrid, int id) { for (int i = 0; i < dataGrid.Rows.Count; i += 1) { MyRowObj row = (MyRowObj)dataGrid.Rows[i].Tag; // or.DataBoundItem; if (row.id == id) { return i; } } throw new ArgumentException("No item with specified id exists in the dataGrid.", "id"); }更多推荐
发布评论