デフォルト値(null、ゼロなど)だけが必要な場合は、組み込みを使用できますElementAtOrDefault
:
Console.WriteLine("{0}", arr.ElementAtOrDefault(5));
ただし、独自の「デフォルト」値 (たとえば 6) を指定する場合は、それを行うための独自の拡張メソッドを提供する必要があります。
Console.WriteLine("{0}", arr.ElementAtOrValue(5, 6));
public static class EnumerableExtensions
{
public static T ElementAtOrValue<T>(
this IEnumerable<T> source, int index, T defaultValue)
{
if (source == null) throw new ArgumentNullException("source");
if (index >= 0)
{
var list = source as IList<T>;
if (list != null)
{
if (index < list.Count) return list[index];
}
else
{
using (var enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
if (index-- == 0) return enumerator.Current;
}
}
}
}
return defaultValue;
}
}