Check if multiple columns contain a value?

Asked

Viewed 70 times

3

Query:

query = query.Where(t =>
                t.campo1.Contains(filter) || t.campo2.Contains(filter) || ......);

I wonder if there is any way that I do not need to keep informing all fields of the table, do something more generic to perform the search.

  • I did not understand why, first, because this query is bad and if the research is done in several fields could use another technique outside the Entity Framework, now if you need to be all fields there is nothing automatic or generic, you do need to pass the fields and maybe this is a single time, sincerity is just what you do and if you are going to do a pure SQL, you will also have to pass the fields, I already think about it.???

  • This does not use EF or other ORM?

1 answer

6


You can search as follows if the data is already materialized Example in https://dotnetfiddle.net/uSnmsJ:

query = query.Where(x => new[] { x.Campo1, x.Campo2, x.Campo3}.Any(s => s.Contains(filter)));

For data not materialized, ie, that will be recovered by some ORM (ex. Nhibernate) maybe this does not work, because it will convert to sql, make the test and inform. Search all data with a Tolist() and search the materialized data. If the table is not too large it will run in an acceptable time.

I updated the example in https://dotnetfiddle.net/uSnmsJ creating a filtered list2 searching for all attributes.

var listaFiltrada2 = lista.Where(m => m.GetType().GetProperties().Any(x => x.GetValue(m, null) != null && x.GetValue(m, null).ToString().Contains("Marco"))).ToList();
  • Would have some form of x.Campo1, x.Campo2, x.Campo3 be altomatic, because I have a table with many columns and want to search in all.

  • @Luizlanza I think the way you’re pretending, just using reflection

  • @Arturotemplário , updated the example as you reported.

  • @Marcoantonioquintal great, but I don’t know if it’s a good idea to do so, it seems very strange

  • @Arturotemplário , also found, I think better to inform in which property seek, the same in list1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.