Returns the first element in the target IEnumerable, or null if the collection is empty. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Returns the first element in the target IEnumerable, or null if the collection is empty.

Demo Code

// All rights reserved.
using System.Collections.Generic;
using System.Collections;
using System;/*from w  ww . j  a  v  a2 s.  c o m*/

public class Main{
        /// <summary>
      /// Returns the first element in the target collection, or null if the collection is empty.
      /// </summary>
      /// <remarks>
      /// TItem must be a reference type, not a value type.
      /// </remarks>
      public static TItem FirstElement<TItem>(IEnumerable<TItem> target)
         where TItem : class
      {
         return FirstElement<TItem>(target, null);
      }
        /// <summary>
      /// Returns the first element in the target collection, or null if the collection is empty.
      /// </summary>
      /// <remarks>
      /// TItem must be a reference type, not a value type.
      /// </remarks>
      public static TItem FirstElement<TItem>(IEnumerable target)
         where TItem : class
      {
         return FirstElement<TItem>(target, null);
      }
        /// <summary>
      /// Returns the first element in the target collection, or the specified <paramref name="defaultValue"/> if the collection is empty.
      /// </summary>
      public static TItem FirstElement<TItem>(IEnumerable target, TItem defaultValue)
      {
         var value = FirstElement(target);
         return value != null ? (TItem)value : defaultValue;
      }
        /// <summary>
      /// Returns the first element in the target collection, or null if the collection is empty.
      /// </summary>
      public static object FirstElement(IEnumerable target)
      {
         if (target is IList)
         {
            var list = (IList)target;
            return list.Count > 0 ? list[0] : null;
         }
         else
         {
            var e = target.GetEnumerator();
            return e.MoveNext() ? e.Current : null;
         }
      }
}

Related Tutorials