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

I am safely browsing the list for such an object:

var someResult = myList.FirstOrDefault(x=>x.SomeValue == "SomethingHere");

If there are no objects matching my criteria, then it someResultwill be null.

But if I only have the index of the object I want, things will not be so good. It seems to me something like this:

try
{
    var someResult = myList[4];
}
catch (ArgumentOutOfRangeException)
{
    someResult = null;
}

I admit that it's not scary to write. But it seems to me that there should be a way to simply return a null list if the index ends with a fake.

Is one (or two) lines sent using existing .net methods ?

(I know that I could easily write an extension method, but I wonder if there is a built-in way to do this.)

+5
source share
4

, LINQ.ElementAtOrDefault(), , .

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

, List<T> , " " . (T).

+10

, C.B.s ElementAtOrDefault - .

...

try/catch:

, .

, . , , , .


LINQ, :

var someResult = myList.Count > 4 ? myList[4] : null;
+11

, LINQ, :

var someResult = myList
            .Select((x, i) => new { X = x, Index = i })
            .FirstOrDefault(x => x.Index == 4);

Enumerable.Select Method (IEnumerable, Func)

Projects each element of a sequence into a new form by including the index of the element.

+3
source

CB answer wins, but I can compete for second place, right?

var someResult = myList.Skip(4).FirstOrDefault();
+2
source

All Articles