DefaultIfEmpty
In this chapter you will learn:
Get to know DefaultIfEmpty operator
Returns the elements of the specified sequence or just returns the type parameter's default value in a singleton collection if the sequence is empty.
using System;//from jav a 2 s .c o m
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
public static void Main() {
List<int> numbers = new List<int>();
foreach (int number in numbers.DefaultIfEmpty()){
Console.WriteLine(number);
}
}
}
DefaultIfEmpty after where clause
using System;/*from j a v a2s.c o m*/
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
public static void Main() {
string[] presidents = {"G", "H", "a", "H", "over", "Jack"};
string jones = presidents.Where(n => n.Equals("H")).DefaultIfEmpty().First();
if (jones != null)
Console.WriteLine("H was found.");
else
Console.WriteLine("H was not found.");
}
}
Next chapter...
What you will learn in the next chapter:
- How to use Distinct operator
- Use Linq Distinct to get the distinct value in an array
- Distinct characters in an array
Home » C# Tutorial » Linq Operators