How to get the first element of IEnumerable

后端 未结 5 2030
情书的邮戳
情书的邮戳 2020-12-29 06:34

Is there a better way getting the first element of IEnumerable type of this:

foreach (Image image in imgList)
{
     picture.Width = (short)image.Columns;
           


        
5条回答
  •  醉梦人生
    2020-12-29 07:00

    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().SingleOrDefault();
    
    
    

    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.

    提交回复
    热议问题