Check if multiple columns contain a value?

3

Query:

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

I would like to know if there is a way that I do not need to keep all fields in the table, do something more general to search.

    
asked by anonymous 27.09.2017 / 14:13

1 answer

5

You can search as follows if the data is already materialized Example at link :

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

For non-materialized data, that is to be retrieved by some ORM (eg NHibernate), this may not work because it will convert to sql, test and report. Search all data with a ToList () and search the materialized data. If the table is not too large this will run in an acceptable time.

I updated the example in link creating a filteredlist2 looking 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();
    
27.09.2017 / 14:24