Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from array if not out of bounds

Tags:

arrays

c#

I'm looking for the most elegant solution to get values from an object[] when the requested index is not out of bounds.

My current solution is as follows:

    public object GetNamedParametersFrom(GenericObject genericObject)
    {
        string nameFromListOne = String.Empty;
        string nameFromListTwo = String.Empty;

        for (int i = 0; i < genericObject.ListOfThings.Count; i++)
        {
            switch (i)
            {
                case 0:
                    nameFromListOne = genericObject.ListOfThings[i].Name;
                    break;
                case 1:
                    nameFromListTwo = genericObject.ListOfThings[i].Name;
                    break;
            }
        }

        return new {
           nameFromListOne,
           nameFromListTwo
        }
    }
like image 840
TheGeekZn Avatar asked May 20 '15 06:05

TheGeekZn


Video Answer


1 Answers

Why not use the built-in ElementAtOrDefault method from Linq?

string[] names =
    { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow",
        "Hedlund, Magnus", "Ito, Shu" };

int index = 20;

string name = names.ElementAtOrDefault(index);
like image 156
Rasmus Avatar answered Oct 06 '22 10:10

Rasmus