c# - Single enumeration with multiple filters -


given following contrived example:

public bool numberofevensequalsnumberofodds(ienumerable<int> numbers) {     var numberofevens = numbers.count(x => x % 2 == 0);     var numberofodds = numbers.count(x => x % 2 != 0);      return numberofevens == numberofodds; } 

this works requires multiple enumerations of collection.

is possible re-write use single linq expression enumerates collection once.

note: i'm trying solve general case of comparing counts 2 filters try , ignore fact sample odd , numbers.

i have included sample .net fiddle

a bit cryptic @ first glance, iterates through collection once.

func<int, bool> iseven = n => n % 2 == 0; func<int, bool> isfive = n => n == 5; int diff = numbers.aggregate(0, (sum, next) => iseven(next) ? sum + 1 : isfive(next) ? sum - 1 : sum); 

for each item in collection, checks 2 conditions. if first condition applies, adds 1 aggregate variable; if second applies, subtracts one. end result difference between number of items meet first criteria , number of items meet second.


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -