text
stringlengths
0
13.4k
{
public Invoice[] Invoices {get;set;}
}
var customers = new[] {
new Customer {
Invoices = new[] {
new Invoice {Id=1},
new Invoice {Id=2},
}
},
new Customer {
Invoices = new[] {
new Invoice {Id=3},
new Invoice {Id=4},
}
},
new Customer {
Invoices = new[] {
new Invoice {Id=5},
new Invoice {Id=6},
}
}
};
var allInvoicesFromAllCustomers = customers.SelectMany(c => c.Invoices);
Console.WriteLine(
string.Join(",", allInvoicesFromAllCustomers.Select(i => i.Id).ToArray()));
Output:
GoalKicker.com – .NET Framework Notes for Professionals
28
1,2,3,4,5,6
View Demo
Enumerable.SelectMany can also be achieved with a syntax-based query using two consecutive from clauses:
var allInvoicesFromAllCustomers
= from customer in customers
from invoice in customer.Invoices
select invoice;
Section 8.2: Where (filter)
This method returns an IEnumerable with all the elements that meets the lambda expression
Example
var personNames = new[]
{
"Foo", "Bar", "Fizz", "Buzz"
};
var namesStartingWithF = personNames.Where(p => p.StartsWith("F"));
Console.WriteLine(string.Join(",", namesStartingWithF));
Output:
Foo,Fizz
View Demo
Section 8.3: Any
Returns true if the collection has any elements that meets the condition in the lambda expression:
var numbers = new[] {1,2,3,4,5};
var isNotEmpty = numbers.Any();
Console.WriteLine(isNotEmpty); //True
var anyNumberIsOne = numbers.Any(n => n == 1);
Console.WriteLine(anyNumberIsOne); //True
var anyNumberIsSix = numbers.Any(n => n == 6);
Console.WriteLine(anyNumberIsSix); //False
var anyNumberIsOdd = numbers.Any(n => (n & 1) == 1);
Console.WriteLine(anyNumberIsOdd); //True
var anyNumberIsNegative = numbers.Any(n => n < 0);
Console.WriteLine(anyNumberIsNegative); //False
GoalKicker.com – .NET Framework Notes for Professionals
29
Section 8.4: GroupJoin
class Developer
{
public int Id { get; set; }
public string Name { get; set; }
}