LINQ ElementAtOrDefault Query Operator

By Peter Bromberg

Returns the element at a specified index in a sequence or a default value if the index is out of range.

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

             int index = 20;

             string name = names.ElementAtOrDefault(index);

           Console.WriteLine(
                 "The name chosen at index {0} is '{1}'.",
                 index,
                 String.IsNullOrEmpty(name) ? "<no name at this index>" : name);

            /*
             This code produces the following output:

             The name chosen at index 20 is '<no name at this index>'.
            */

LINQ ElementAtOrDefault Query Operator  (591 Views)