SEARCH
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Prev | Current Page 305 | Next

Satheesh, N Kumar

"LINQ Quickly"


Standard Query Operators
[ 212 ]
FirstOrDefault
This operator is very similar to the First operator, but it returns the default value if
the source does not have any elements in it.
public static TSource FirstOrDefault
(
IEnumerable source
)
public static TSource FirstOrDefault
(
IEnumerable source,
Func predicate
)
In the following code, FirstOrDefault returns a default value if the source
sequence does not have any value. In the first example, the integer array is empty.
The FirstOrDefault operator returns a zero in this case.
int[] numbers = {};
int firstNumber = numbers.FirstOrDefault();
Console.WriteLine("The First number in the list is: {0}",
firstNumber);
The following example shows an empty string array. In this case, the operator
returns nothing. We can check the value using IsNullOrEmpty, and then return the
default value or a message.
string[] strings = { };
string firstStringwithCondition = strings.FirstOrDefault(str =>
str == "Chocolate");
Console.


Pages:
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317