copy all elements from linked list to array - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:List

Description

copy all elements from linked list to array

Demo Code


using System.Text;
using System.Runtime.InteropServices;
using System.Linq;
using System.Collections.Generic;
using System;/*from  w  w  w. ja  v  a  2  s .com*/

public class Main{
        /// <summary>
      /// copy all elements from linked list to array
      /// </summary>
      /// <typeparam name="T">element type</typeparam>
      /// <param name="list">list which elements will be copied to array</param>
      /// <returns>array filled with elements from list, or null if list was null</returns>
      public static T[] ToArray<T>(this LinkedList<T> list) {
         if (list == null) {
            return null;
         }
         var cnt = list.Count;
         if (cnt <= 0) {
            return new T[0];
         }
         var array = new T[cnt];
         int i = 0;
         foreach (var e in list) {
            array[i] = e;
            ++i;
         }
         return array;
      }
}

Related Tutorials