views:

405

answers:

4

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

foreach (Image image in imgList)
{
     picture.Width = (short)image.Columns;
     picture.Height = (short)image.Rows;
     break;
}

This is the exact declaration of the type:

public class ImageList : IEnumerable, IDisposable
+11  A: 
var firstImage = imgList.Cast<Image>().First();
Mark Seemann
I didn't tried it yet, but this is make sense that it will work.
Mendy
@Mark, is Cast required.. cant we just use "var firstImage = ImgList.First()" ??
Ramesh Vel
@Ramesh: `Cast` is required in this case as `First` is implemented for `IEnumerable<T>` but `ImageList` only implements `IEnumerable`.
Brian Rasmussen
@Ramesh Vel, you can't use imgList.First() as it's not a generic IEnumerable<T> before casting it.
JonC
@Brian, @jonC, sorry guys i wasnt aware of that "ImageList only implements IEnumerable" :(
Ramesh Vel
+5  A: 

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

Jarrett Meyer
+1  A: 

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

JonC
A: 

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

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

wasatz
Actually I know Linq very well, but the `IEnumerable` was confusing since regularly work with `IEnumerable<T>`.
Mendy