Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C# Advent 2020
// Generate numbers from -10 .. 100
var numbers = Enumerable.Range(-10, 111);
// Determines all positive numbers that are divisible by 6
var positiveDivisbleBySix = numbers
.Where(x=>x > 0) // iterates through the whole list (111 comparisons, returning 100 results)
.Where(x=>x % 2 == 0) // iterates through the new list (100 comparisons, returning 50 results)
.Where(x=>x % 3 == 0); // iterates through the new list (50 comparisons, returning 16 results)
// Overall metrics: 261 comparisons over 111 total elements)
// Generate numbers from -10 .. 100
var numbers = Enumerable.Range(-10, 111);
var positiveDivisibleBySix = numbers.Where(x => x > 0 && x % 2 == 0 && x % 3 == 0);
Func<T, bool> CombinePredicateWithAnd<T>(Func<T, bool> a, Func<T, bool> b)
{
return x => a(x) && b(x);
}
Func<int, bool> isPositive = x => x > 0;
Func<int, bool> isEven = x => x % 2 == 0;
Func<int, bool> isDivisibleByThree = x => x % 3 == 0;
var predicates = new List<Func<int, bool>> {isPositive, isEven, isDivisibleByThree};
var combinedPredicate = predicates.Aggregate(...., ....);
Func<int, bool> combinedPredicateWithAnd(Func<int, bool> a, Func<int, bool> b)
{
return x => ...;
}
Func<int, bool> combinedPredicateWithAnd(Func<int, bool> a, Func<int, bool> b)
{
return x => ... && ...;
}
Func<int, bool> combinedPredicateWithAnd(Func<int, bool> a, Func<int, bool> b)
{
return x => a(x) && b(x);
}
Func<int, bool> andIdentity = _ => true;
var combinedPredicate = predicates.Aggregate(andIdentity, CombinePredicateWithAnd);
// Define the predicates
Func<int, bool> isPositive = x => x > 0;
Func<int, bool> isEven = x => x % 2 == 0;
Func<int, bool> isDivisibleByThree = x => x % 3 == 0;
var predicates = new List<Func<int, bool>> {isPositive, isEven, isDivisibleByThree};
// Defining the Aggregate functions
Func<int, bool> andIdentity = _ => true;
Func<int, bool> combinedPredicateWithAnd(Func<int, bool> a, Func<int, bool> b)
{
return x => a(x) && b(x);
}
// Combining the predicates
Func<int, bool> combinedAndPredicate = predicates.Aggregate(andIdentity, combinedPredicateWithAnd);
// The new solution
// Generate numbers from -10 .. 100
var numbers = Enumerable.Range(-10, 111);
var positiveDivisbleBySix = numbers.Where(combinedAndPredicate);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment