IndexOrDefault that functions like FirstOrDefault I don't know why this is not in the .NET Library, but I need to be able to use an index against a list and not have it throw an exception if it is outside the bounds of the list.

This is what I came up with:

public static class LinqHelpers
{
    public static TListType IndexOrDefault&lt;TListType&gt;(this List&lt;TListType&gt; list,
                                                      int index)
    {
        var count = list.Count();           
        if (index &gt; count -1)
            return default(TListType);              
        if (index &lt; 0)
            return default(TListType);          
        return list[index];
    }
}


This is my test:

List&lt;string&gt; somelist = new List&lt;string&gt; {"B", "A", "Q", "a", "t", "h"};
for (int i = -100; i &lt; 100; i++)
{
    Console.WriteLine(somelist .IndexOrDefault(i)); 
}   


I would appreciate any advice on missing error handling or if I am reinventing an already existing feature.  I also would not mind advice on a way to use an IEnumerable instead of a List with out iterating the IEnumerable more than once.
public static TListType IndexOrDefault&lt;TListType&gt;(this List&lt;TListType&gt; list, int index)



You're extending a concrete type, and the type parameter's name is misleading - it's not the type of the list, it's the type of its items. I'd just call it T. IList&lt;T&gt; calls it T, so I don't see a problem with T ;)

You should be extending an interface, in this case probably an IEnumerable&lt;T&gt;, like LINQ extension methods do.


var count = list.Count();



You're iterating the List&lt;T&gt; through its IEnumerable&lt;T&gt; interface (doesn't apply to List&lt;T&gt; because a List&lt;T&gt; is also an ICollection&lt;T&gt; see @svick's comment below, but in other cases that would be \$O(n)\$ already), and you haven't tried to find anything yet! A List&lt;T&gt; doesn't need to be iterated to retrieve its count, just use the Count property getter, like this:

var count = list.Count;


Actually this whole block:


    var count = list.Count();           
    if (index &gt; count -1)
        return default(T);              
    if (index &lt; 0)
        return default(T);
    return list[index];



Could be simplified to:

if (index &gt; list.Count - 1 || index &lt; 0)
{
    return default(T)
}

return list[index];




But that's still extending a List&lt;T&gt;. You're going to want to extend IEnumerable&lt;T&gt; instead... but the method you're implementing already exists in System.Linq:

public static T IndexOrDefault&lt;T&gt;(this IEnumerable&lt;T&gt; source, int index)
{
    return source.ElementAtOrDefault(index);
}


You're duplicating the functionality of the IEnumerable&lt;T&gt;.ElementAtOrDefault extension method.