It seems as if only DataSet, DataTable and DataView can be used as sources when you want to use BindingSource.Find
. I'm binding IQueryable and IEnumerable to my binding source, but would very much like to enjoy the 'convenience' of the BindingSource.Find
method, without writing reams of code myself, as time is of the essence.
Does anyone know of an existing implementation, or at least detailed 'how to' article that can help me achieve this?
You can use the Type.GetProperty and Array.FindIndex methods to create a concise extension method.
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));
}