C# LINQ Zip: find at least one pair -
i have 2 arrays , i'd know if condition satisfy at least 1 pair lists.
minimum reproducing code:
var boxtypes = new string[] { "banana", "apple", "apple", "banana" }; var boxsizes = new int[] { 31, 16, 35, 8 }; int bigboxsize = 20; bool hasbigapplebox = boxtypes.zip(boxsizes, (type, size) => (type == "apple" && size >= bigboxsize) ? 1 : 0) .sum() > 0;
this code iterates through pairs. 1 pair enough.
any suggestion improve code?
short answer: use any(result => result > 1)
long answer: use of sum()
going evaluate entire collection, , using any()
evaluate until first true
condition met.
example:
boxtypes.zip(boxsizes, (type, size) => (type == "apple" && size >= bigboxsize) ? 1 : 0) .any(result => result == 1)
it's worth noting (type == "apple" && size >= bigboxsize) ? 1 : 0
predicate can simplified in case type == "apple" && size >= bigboxsize)
.
with this, statement becomes:
boxtypes.zip(boxsizes, (type, size) => type == "apple" && size >= bigboxsize) .any()
Comments
Post a Comment