Get Element from IEnumerable - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Get Element from IEnumerable

Demo Code


using System.Collections.Generic;
using System.Collections;
using System;/*from w  w w .  ja v a2 s  .co  m*/

public class Main{
        public static T GetElement<T>(IEnumerable<T> collection, int at)
        {
            int idx = 0;
            foreach (T obj in collection)
            {
                if (idx == at)
                    return obj;
                idx++;
            }

            throw new ArgumentOutOfRangeException("at", "expected value less then " + idx);

        }
        public static object GetElement(IList list, int idx, object notExistValue)
        {
            if (idx < 0 || idx > list.Count - 1)
                return notExistValue;
            return list[idx];
        }
}

Related Tutorials