-1

Is there a way to do a contains search in linq across all the rows at once rather than list them out.

At the moment I am doing

    Data.Where(
        x => x.Name.Contains(searchValue) ||
        x.Address.Contains(searchValue) || 
        x.Id.ToString().Contains(searchValue)... etc

What would I like to do is pass in a generic and have it search across all the data in the rows?

e.g. Data.Where(x => row.Contains(searchValue))

TheAlbear
  • 5,507
  • 8
  • 51
  • 84

2 Answers2

0

Duplicate of LINQ query any of the properties contains string

You can use reflection but it isn't good for performance

list.Where(x => x.GetType()
            .GetProperties()
            .Any(p =>
            {
                var value = p.GetValue(x);
                return value != null && value.ToString().Contains("some string");
            }));

EDIT: Like Fabio said this will filter list in memory, not in sql.

  • 4
    Will not work for SQL, OP have SQL tag, assume that linq will generate sql – Fabio Jun 26 '18 at 09:35
  • 1
    Side note to the Edit: Filtering in memory i.e. `Data.AsEnumerable().Where(...)` even if it's possible can well appear be *inefficient* (you fecth a *long cursor* into memory and then obtain just a *few records* after filtering) – Dmitry Bychenko Jun 26 '18 at 09:42
-2

You can add a property for your data type with a getter method that joins other properties:

public string JoinedProperty{
   get{
      return Name+" "+Id.ToString();
   }
}

and then this code can help you

Data.Where(
    x => x.Contains(searchValue) ... etc
Zer0
  • 7,191
  • 1
  • 20
  • 34
Nima Yazdi
  • 27
  • 9