是否有任何已知的 IBIndingList 实现支持 Find 方法,适用于 LINQ



当您想使用BindingSource.Find时,似乎只有DataSetDataTableDataView可以用作源。我正在将IQueryableIEnumerable绑定到我的绑定源,但非常希望享受BindingSource.Find方法的"便利",而无需自己编写大量代码,因为时间至关重要。

有谁知道现有的实现,或者至少是详细的"如何"文章可以帮助我实现这一目标?

可以使用

Type.GetProperty 和 Array.FindIndex 方法来创建简洁的扩展方法。

public static int Find<T>(this IEnumerable<T> items, string propertyName, Object key)
{
    PropertyInfo property = typeof(T).GetProperty(propertyName);
    if(property == null)
    {
        throw new ArgumentException(String.Format("Type {0} contains no property named "{1}". ",
                                    typeof(T).Name, propertyName), "propertyName");
    }
    return Array.FindIndex(items.ToArray(), i => Object.Equals(property.GetValue(i, null), key));       
}

最新更新