Generation Operations
Generation operations spawn new sequences of values.
The query operator methods used to perform these operations follow: DefaultIfEmpty, Empty, Range, and Repeat.
The DefaultIfEmpty method replaces an empty collection with a singleton collection of default values. Review its syntax below:
public static IEnumerable<TSource> DefaultIfEmpty<TSource>( this IEnumerable<TSource> source )
Review an example of its use below:
class Boot { public string Name { get; set; } public int Quantity { get; set; } } public static void Example() { List<Boot> boots = new List<Boot>{ new Boot { Name="Fashion", Quantity=15 }, new Boot { Name="Work", Quantity=10 }, new Boot { Name="Casual", Quantity=20 } }; foreach (Boot boot in boots.DefaultIfEmpty()) { Console.WriteLine(boot.Name); } }
This example operates on an empty sequence:
List<int> quantities = new List<int>(); foreach (int quantity in quantities.DefaultIfEmpty()) { Console.WriteLine(quantity); }
The Empty method simply returns an empty collection. Review its syntax below:
public static IEnumerable<TResult> Empty<TResult>()
Review an example of its use below:
IEnumerable<decimal> novalues = Enumerable.Empty<decimal>();
Review another example which partners Empty with Aggregate:
string[] team1 = { "Hart, Timmy" };
string[] team2 = { "Adrien, Teddy", "Anderson, Henry B.", "Heder, Kwame",
"Ikamoto, Fred" };
string[] team3 = { "Singh, Jakob", "Appiah, Michael", "Anderson, Henry B.", "Lame,
Skylar", "McWaffle, Brad" };
List<string[]> teamList = new List<string[]> { team1, team2, team3 };
// Only include arrays with 4 or more elements
IEnumerable<string> allTeams =
teamList.Aggregate(Enumerable.Empty<string>(),
(current, next) => next.Length > 3 ? current.Union(next) :
current);
foreach (string member in allTeams)
{
Console.WriteLine(member);
}
The Range method spawns a collection containing a number sequence. Review its syntax below:
public static IEnumerable<int> Range( int start, int count )
Review an example of its use below:
IEnumerable<int> squaredVal= Enumerable.Range(1, 15).Select(y => y * y); foreach (int value in squaredVal) { Console.WriteLine(value); }
The Repeat method spawns a collection containing a single repeated value. Review its syntax below:
public static IEnumerable<TResult> Repeat<TResult>( TResult element, int count )
Review an example of its use below:
IEnumerable<string> statements = Enumerable.Repeat("What silence looks like.", 21); foreach (String strg in statements) { Console.WriteLine(strg); }