0

I have 4 rows in my DB (example), I load data from DB to DataModel like Regex for columns Code and Serie:

Id;Code;Serie
1;XXX;XXX
2;XXX;XXX_A
3;WWW;YYY_A|YYY_B
4;CCC;XXX_A

When I use LINQ query below with input parameters Code = XXX and Serie = XXX_A, I got 2 results, but the right result is only got a row with ID == 2

model = _seriesData.Where(s => (s.Code.IsMatch(code) && s.Type.IsMatch(serie)));

I do not know where is a problem, but LINQ works only with one parameter

In my model column Code and Serie are Regex types

UPDATE

For Code row Regex I also use regex like this XXX_A|XXX_B|YYY_A Data in the _seriesData variable are ok, but the result is wrong

DataModel

public class SerieModel
{
    public Regex Type { get; set; } // name of serie
    public Regex Code { get; set; }
}

Does anybody help me?

5
  • Bear in mind that almost any function call in a .Where clause will cause the data to be retrieved from the database and the clause will run locally. This may involve huge numbers of records being sent over your network and be very inefficient. Commented Apr 30, 2019 at 9:02
  • Seems weird! If you test with .equals or '==' what do you get? Commented Apr 30, 2019 at 9:05
  • Try this: model = _seriesData.Where(s => (s.Code==code && s.Serie==serie)).FirstOrDefault(); Commented Apr 30, 2019 at 9:19
  • Use FirstOrDefault(); is not a solution because I do not know if my row which I want to find is first in DB or not, also == is not possible to use for Regex datatype, Type and Serie is same, only with another names Commented Apr 30, 2019 at 9:23
  • You should one use Regex when string class methods cannot be used. Regex is much less efficient than string class. All you need is a simple comparison : model = _seriesData.Where(s => (s.Code == code) && (s.Type == serie)); Commented Apr 30, 2019 at 9:40

1 Answer 1

4

This happens probably because your regex matches substring but not whole string. Whole string is matched by wrapping your pattern in ^...$ symbols:

new Regex("XXX").IsMatch("XXX");     //true
new Regex("XXX").IsMatch("XXX_A");   //true <- heh, didn't expect that?
new Regex("^XXX$").IsMatch("XXX");   //true
new Regex("^XXX$").IsMatch("XXX_A"); //false <- this is what you want

So, either change data in your columns to:

Id;Code;Serie
1;^XXX$;^XXX$
2;^XXX$;^XXX_A$
3;^WWW$;^(YYY_A|YYY_B)$
4;^CCC$;^XXX_A$

Or change it on deserialization to row:

public class SerieModel
{
    public Regex Type { get; set; } // <- put here wrapped regex.
    public Regex Code { get; set; } // <- put here wrapped regex.
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.