Home > Software design >  Dynamic predicate in where clause
Dynamic predicate in where clause

Time:11-16

I have the below search all fields condition where I specify the column names(Col1,Col2,Col3) I want the column names to be dynamic values which is in a different string array. How is that possible ?

rows is a list of EnumerableRowCollection rows which contains all data and then i apply the contains filter which will filter out the rows which contains the value in objSearch.SearchAllFields

if (objSearch.SearchAllFields != "")
                {
                    rows = results.Where(x => new[]
                                           { x.Field<string>("Col1"),
                                             x.Field<string>("Col2"),
                                             x.Field<string>("Col3")
                                           }.Any(s => s.ToLowerInvariant().Contains(objSearch.SearchAllFields.ToLowerInvariant())));
                }

something like given below which is wrong and doesnt work i know that.

string[] AllColumns = objProp.Select(p => p.Name).ToArray();
                if (objSearch.SearchAllFields != "")
                {
                    rows = results.Where(x => AllColumns.Any(s => s.ToLowerInvariant().Contains(objSearch.SearchAllFields.ToLowerInvariant())));
                }

Original

Col1     Col2    Col3 
test     abc    pqr
2        abc    123
asd      test    xyz 

Expected

Col1     Col2    Col3 
test     abc    pqr
asd      test    xyz

CodePudding user response:

You've tried to change from

new[]
{ x.Field<string>("Col1"),
  x.Field<string>("Col2"),
  x.Field<string>("Col3")
}.Any(...

To this:

AllColumns.Any(...

Assuming AllColumns is IEnumerable<string>, I believe this would be the right solution:

rows = results.Where(row => AllColumns.Select(column => row.Field<string>(column)).Any(...
  • Related