How to get the first element of IEnumerable

后端 未结 5 2050
情书的邮戳
情书的邮戳 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:03

    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!

提交回复
热议问题