c# - Select interval linq -
is there way linq
select numbers shortcut criteria. this: have numbers 1 10000
. criteria (4012..4190|4229)
, meaning take numbers between 4012 4190
, number 4229
:
static int[] test(string criteria) { // criteria 4012..4190|4229 // select numbers lab criteria met int[] lab = enumerable.range(0, 10000).toarray(); return lab; }
if criteria
string
, need way parse it, func<int, bool
, it's not linq specific. in end you'll need this:
func<int, bool> predicate = parse(criteria); return lab.where(predicate).toarray();
where basic implementation of parse
might follows:
public static func<int, bool> parse(string criteria) { var alternatives = criteria .split('|') .select<string, func<int, bool>>( token => { if (token.contains("..")) { var between = token.split(new[] {".."}, stringsplitoptions.removeemptyentries); int lo = int.parse(between[0]); int hi = int.parse(between[1]); return x => lo <= x && x <= hi; } else { int exact = int.parse(token); return x => x == exact; } }) .toarray(); return x => alternatives.any(alt => alt(x)); }