[ACCEPTED]-How to get the first element of IEnumerable-html-lists

Accepted answer
Score: 36
var firstImage = imgList.Cast<Image>().First();


Score: 10

If you can't use LINQ you could also get 3 the enumerator directly by imgList.GetEnumerator() And then do 2 a .MoveNext() to move to the first element. .Current will then 1 give you the first element.

Score: 6

The extension .First() will grab the first item 5 in an enumerable. If the collection is empty, it 4 will throw an exception. .FirstOrDefault() will return a 3 default value for an empty collection (null 2 for reference types). Choose your weapon 1 wisely!

Score: 0

Might be slightly irrelevant to your current 9 situation, but there is also a .Single() and a .SingleOrDefault() which 8 returns the first element and throws an 7 exception if there isn't exactly one element 6 in the collection (.Single()) or if there are more 5 than one element in the collection (.SingleOrDefault()).

These 4 can be very useful if you have logic that 3 depends on only having a single (or zero) objects 2 in your list. Although I suspect they are 1 not what you wanted here.

Score: 0

I had an issue where I changed my datasource 11 from a bindingsource to an entity framework 10 query.

var query = dataSource as IQueryable;
var value = query.Where("prop = @0", value).Cast<object>().SingleOrDefault();

With entity framework this throw an 9 exception `Unable to cast the type 'customer' to 8 type 'object'. LINQ to Entities only supports 7 casting EDM primitive or enumeration types.

The 6 class where my code was did not have a reference 5 to the lib with the model so ...Cast<customer> was not possible.

Anyway 4 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 3 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<MethodInfo> singleOrDefaultMethod 
         = new Lazy<MethodInfo>(() =>
                 "SingleOrDefault", BindingFlags.Static | BindingFlags.NonPublic));

    private static T SingleOrDefault<T>(IEnumerable<T> enumerable)
        return enumerable.SingleOrDefault();

feel 2 free to implement caching per type to improve 1 performance.

More Related questions