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

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -