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
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With