Is there a better way getting the first element of IEnumerable type of this:
foreach (Image image in imgList)
{
picture.Width = (short)image.Columns;
I had an issue where I changed my datasource from a bindingsource to an entity framework query.
var query = dataSource as IQueryable;
var value = query.Where("prop = @0", value).Cast
With entity framework this throw an exception `Unable to cast the type 'customer' to type 'object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
The class where my code was did not have a reference to the lib with the model so ...Cast
was not possible.
Anyway I used this approach
var query = dataSource as IQueryable;
var targetType = query.GetType().GetGenericArguments()[0];
var value = query.Where("prop = @0", value).SingleOrDefault(targetType);
in conjunction with an IEnumerable extension which uses reflection
public static object SingleOrDefault(this IEnumerable enumerable, Type type)
{
var method = singleOrDefaultMethod.Value.MakeGenericMethod(new[] { type });
return method.Invoke(null, new[] { enumerable });
}
private static Lazy singleOrDefaultMethod
= new Lazy(() =>
typeof(Extensions).GetMethod(
"SingleOrDefault", BindingFlags.Static | BindingFlags.NonPublic));
private static T SingleOrDefault(IEnumerable enumerable)
{
return enumerable.SingleOrDefault();
}
feel free to implement caching per type to improve performance.