当您想使用BindingSource.Find
时,似乎只有DataSet,DataTable和DataView可以用作源。我正在将IQueryable和IEnumerable绑定到我的绑定源,但非常希望享受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));
}