LINQ ma sprytne rozszerzenie ElementAtOrDefault:
if (list.ElementAtOrDefault(a) != null)
{
// do the magic
}
Ewentualnie stworzyć metodę rozszerzającą dla wygody:
public static class CollectionExtensions
{
public static bool ElementAtIndexExists(this IEnumerable<T> collection, int index)
{
return collection.ElementAtOrDefault(index) != null; // lub default, jeżeli T to prymityw
}
}
Lub po prostu przechwycić wyjątek ArgumentOutOfRangeException dla wywołania indeksera listy:
try
{
// jakieś wywołanie list[a]
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"Wystąpił problem z wykonaniem operacji:{Environment.NewLine}{ex.Message}");
}