LINQ search / match

Let's assume we have an array like this:

 var caps = new[] { "1512x", "001xx", "27058", "201xx", "4756x" };

      

(original array is huge and comes from another linq query)

I need to create a LINQ operator taking a value and try to match one of the values ​​in the foreseen array.

For example, if I use "15121", I need to match the value "1512x" in the array and return it. Obviously if I use "27058" it finds an exact match and just returns it.

Is this possible in LINQ? The "wildcard" char is in the array "x", but I can change it.

Thanks in advance! Valerio

+3


source to share


2 answers


You can use regular expressions:

var value = "15121";
var caps = new[] { "1512x", "001xx", "27058", "201xx", "4756x" };
var match = caps
  .FirstOrDefault(c => new Regex("^" + c.Replace("x", "[0-9]") + "$").IsMatch(value));
if (match != null)
  Console.WriteLine("{0} matches {1}", value, match);

      



"pattern" is 001xx

converted to regular expression, ^001[0-9][0-9]$

and so on. Then the first matching regular expressions will be found.

But if it caps

is huge, it may not work as well because every regex must be compiled and converted to a state machine until a match is found.

+6


source


Assuming you have a predicate method, something like this (or something equivalent using Regex, as described in another answer):

static bool Match(string pattern, string exact)
{
    if(pattern.Length != exact.Length) return false;
    for(var i = 0; i < pattern.Length; i++)
        if(pattern[i] != exact[i] && pattern[i] != 'x') 
            return false;
    return true;
}

      



Then the LINQ query might look like this:

var found = caps.Single(x => Match(x, yourSearch));

      

+4


source







All Articles