1
Hello, I come from the web (javascript) and I have the habit of working with OO mixing a little functional paradigm. Imagine the following situation.
- I have a CC I have to check if it exists in the database;
- I have no control over the formatting, so I do a treatment to remove your mask and check what’s left;
- From that, I access a
DbContext
using Entityframework, and checking, based on the result of a Regex whether or not CPF exists in the database.
Normally on the web I would do something like:
var list = [ ... ]; // aqui seria um mockup do banco de cpf's ou o retorno
// de um webservice, etc...
var cpf = '000.000.000-00';
function exists(cpf, list) {
var rx = /[-/.]/g;
return list.filter(x => x.replace(rx,'') === cpf.replace(rx,'')).length > 0;
}
console.log(exists(cpf, list));
But when trying to do something similar in C# I am having a message that I cannot compare the result of 2 regex directly. My code is as follows:
// classe DbContext
public class Db: DbContext
{
public virtual DbSet<Pessoa> Pessoa { get; set; }
}
// classe Model (de acesso ao banco de dados)
public class Pessoa
{
// propriedades (reduzidas para brevidade)
public string Cpf { get; set; }
// método de consulta
public bool exists(string cpf)
{
using (var db = new Db())
{
var rx = new Regex("[-/.]+");
return db.Pessoa.Where(x => rx.Replace(x.Cpf).Equals(rx.replace(cpf,""))).First() != null;
}
}
}
Cannot make comparisons with regex in c# or the shape I made is unclear?
I’ve had problems like that using expressions on
Where
, maybe ride different solves, something likevar pessoa = (from p in db.Pessoa where rx.Replace(x.Cpf).Equals(rx.replace(cpf,"")) select p).First()
– Ricardo Pontual
regex to check if there is ? if you have already cleaned the string, just check...
db.Pessoa.Any(x => x.Cpf == _cpf)
– Rovann Linhalis
@Rovannlinhalis the idea is exactly do not clean out, but take advantage of it inside the Linq... even so I will try with the
.Any
– LeandroLuk