How to get the first element of IEnumerable

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

    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.

提交回复
热议问题