Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first element of IEnumerable

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
like image 952
Fitzchak Yitzchaki Avatar asked Feb 23 '10 09:02

Fitzchak Yitzchaki


2 Answers

var firstImage = imgList.Cast<Image>().First();
like image 144
Mark Seemann Avatar answered Oct 04 '22 14:10

Mark Seemann


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.

like image 33
JonC Avatar answered Oct 04 '22 14:10

JonC