Search code examples
c#linq.net-coredynamic-linq

Search single value in multiple columns with Linq.Dynamic.Core


My test case scenario is about a search textbox and a grid with the search results.

By using the following currently, i search only on the first column.

foreach (GridColumn s in columns)
{
   data = data.Where(string.Format("{0}.Contains(@0)", s.PropertyName), searchValue);
   break; 
}

As you already guessed, if i remove the break statement, no results are returned due to the lack of OR statements between the foreach loop.

How can i search for a single value in multiple columns with Linq.Dynamic.Core?


Solution

  • With System.Linq.Dynamic.Core you could use code like this:

    var xx = new [] { "ax", "bx", "cy", "dz" };
    
    var columns = new[] { "x", "y" };
    
    string query = string.Join(" or ", columns.Select(c => $"it.Contains(\"{c}\")"));
    
    var result = xx.AsQueryable().Where(query);
    

    Example in LinqPad: enter image description here