Rani Radcliff
Rani Radcliff

Reputation: 5076

Find all records that match a pattern in collection

I have been banging my head on this one. I need to extract all records from a collection where a field contains "[" + Any Number + "]". Basically [0], [1], [2], etc. If it has a number enclosed in brackets, I need it. I tried:

allvalues.Where(p => p.Path.Contains(property.Path) && p.Path.Contains(p.Path.Split('[', ']')[1])

But if it does not exist, I get the the dreaded error

Index out of bounds

I cannot use the following:

allvalues.Where(p => p.Path.Contains(property.Path) && p.Path.Contains('[') 

because there are some paths that contain "[]" and I don't want those.

I thought about Regex.IsMatch, but since I was unable to find any such examples, I assume that you cannot mix it with the lambda.

Upvotes: 2

Views: 385

Answers (1)

Michał Turczyn
Michał Turczyn

Reputation: 37480

You were right about regular expressions, they seem like a good fit here.

Use pattern \[\d+\]

Explanation:

\[ - match [ ltierally

\d+ - match one ore more digtis

\] - match ] literally

Usage in code:

allvalues
  .Where(p => p.Path.Contains(property.Path) && Regex.Match(p.Path, @"\[\d+\]").Success);

Upvotes: 4

Related Questions