Find an element at an index in LinkedList - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:LinkedList

Description

Find an element at an index in LinkedList

Demo Code


using System.Text;
using System.Collections.Generic;
using System;/*from   w  ww.jav a  2 s  . c om*/

public class Main{
        /// <summary>
        /// Find an element at an index
        /// </summary>
        /// <param name="source"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public static T ElementAt<T>(LinkedList<T> source, int index)
        {
            LinkedListNode<T> node = source.First;
            for (int i = 0; i < index; i++)
            {
                if (node == null)
                    throw new IndexOutOfRangeException();
                node = node.Next;
            }

            return node.Value;
        }
        /// <summary>
        /// Get first item in a collection
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collection"></param>
        /// <returns></returns>
        public static T First<T>(ICollection<T> collection)
        {
            foreach (T item in collection)
                return item;
            return default(T);
        }
}

Related Tutorials