如何使用C#根据对象值查找行的索引?

| 我有一个datagridview,我想从中删除一个特定的行(datagridview没有数据绑定)。要删除,我需要该行的索引。 Datagridview项目都是对象。此时,我所拥有的只是对象的ID(一个属性)。我想知道datagridview中包含id对象的行的索引,比如说2。 我该如何完成?还是有另一种方法基于对象的值删除行?     
已邀请:
        可能有一种更干净的方法,但是使用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\");
}
    
        如果您的DataGridView的DataSource是BindingSource,并且基础列表实现了FindCore,则可以使用BindingSource Find()方法,如下所示:
BindingList<YourObject> objectList = new BindingList<YourObject>();
BindingSource source = new BindingSource();
source.DataSource = objectList;

dataGridView1.DataSource = source;

private int GetIndexOfItemById(int id)
{
    return source.Find(\"Id\", id);
}
可以说这是正确的方法,并且可能会给您带来更好的性能(您可能不需要)。但是,Microsoft并没有使此操作变得容易。框架BindingList对象没有实现FindCore,因此您将需要创建自己的IBindingList()(以及实现排序,因为您可能也希望这样做)。 这是支持Find()的IBindingList实现的代码(取自MSDN)。
protected override bool SupportsSearchingCore
{
    get
    {
        return true;
    }
}

protected override int FindCore(PropertyDescriptor prop, object key)
{
    // Get the property info for the specified property.
    PropertyInfo propInfo = typeof(T).GetProperty(prop.Name);
    T item;

    if (key != null)
    {
        // Loop through the items to see if the key
        // value matches the property value.
        for (int i = 0; i < Count; ++i)
        {
            item = (T)Items[i];
            if (propInfo.GetValue(item, null).Equals(key))
                return i;
        }
    }
    return -1;
}
如果将DataTable用作数据源,则可以立即使用Find()行为,但是由于您说有自定义对象的列表,因此可能不是。     
        一种LINQ的方法。
var row = dataGrid.Rows.OfType<MyRowObj>().FirstOrDefault(r => r.id == id);
if (row != null) {
   var rowIndex = dataGrid.Rows.IndexOf(row);
   // ... if you need the row index
} else {
   // cry :(
}
在这里,我使用
Rows.IndexOf
-否则索引可以在LINQ查询中使用。关于SO的例子很多。 (就像添加到他的答案中的一个ICR一样:) 快乐的编码。     
        
var query = from DataGridViewRow row in _dataGrid.Rows 
            where  ((DataRowView)row.DataBoundItem).Row == boundedRow
            select row;

if (query.Count() > 0)
{
    // actions
}
    

要回复问题请先登录注册