Get the first item from an IEnumerable - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Get the first item from an IEnumerable

Demo Code


using System.Text;
using System.Collections.Generic;
using System.Collections;
using System;/*from www  .  j av  a 2 s.c om*/

public class Main{
        /// <summary>
      /// Get the first item from an IEnumerable
      /// </summary>
      /// <param name="collection"></param>
      /// <returns>return null if the collection is empty</returns>
      /// <remarks>
      /// This method depends on the sequence of the collection, 
      /// if the collection does not have a sequence, then it is unpreditable that which item will be returned.
      /// </remarks>
      public static object GetFirst(IEnumerable collection) {
         object retVal = null;
         IEnumerator en = collection.GetEnumerator();
         if (en.MoveNext()) retVal = en.Current;

         return retVal;
      }
}

Related Tutorials