如何使用C#基于对象值查找行的索引?(How to find index of a row based on the object value using C#?)

编程入门 行业动态 更新时间:2024-10-06 06:39:55
如何使用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"); }

更多推荐

本文发布于:2023-07-17 10:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1142720.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   索引   对象   find   object

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!