Is there a concise built-in way to get a list item by index that is not going to throw an exception?

.net, c#, linq, list

Solution

You may be able to use the LINQ extension .ElementAtOrDefault() to achieve what you want.

List<Foo> foos = new List<Foo>();
Foo element = foos.ElementAtOrDefault(4);

However, you need to be careful that your generic type to `List<T>` is a reference type or a string, so the "default" returned to you is actually null. The default you get back is default(T).

Problem

I safely search a list for an object like this: ``` var someResult = myList.FirstOrDefault(x=>x.SomeValue == "SomethingHere"); ``` If there are no objects that match my criteria then `someResult` is going to be null. But if I only have the index of the object I want, things are not so nice. I seem to have to so something like this: ``` try { var someResult = myList[4]; } catch (ArgumentOutOfRangeException) { someResult = null; } ``` I admit that is not terrible to have to write. But it seems to me that there should be a way to just have the list return null if the index ends up being bogus. Is there away to have a one (or two) line look up using existing .net methods? (I know I could easily write an extension method, but I am wondering if there is a built in way to do this.)

Original source