How to dynamically add OR operator to WHERE clause in LINQ

后端 未结 4 799
花落未央
花落未央 2020-11-30 07:36

I have a variable size array of strings, and I am trying to programatically loop through the array and match all the rows in a table where the column \"Tags\" contains at le

4条回答
  •  无人及你
    2020-11-30 07:57

    I recently created an extension method for creating string searches that also allows for OR searches. Blogged about here

    I also created it as a nuget package that you can install:

    http://www.nuget.org/packages/NinjaNye.SearchExtensions/

    Once installed you will be able to do the following

    var result = db.Songs.Search(s => s.Tags, strArray);
    

    If you want to create your own version to allow the above, you will need to do the following:

    public static class QueryableExtensions  
    {  
        public static IQueryable Search(this IQueryable source, Expression> stringProperty, params string[] searchTerms)  
        {  
            if (!searchTerms.Any())  
            {  
                return source;  
            }  
    
            Expression orExpression = null;  
            foreach (var searchTerm in searchTerms)  
            {  
                //Create expression to represent x.[property].Contains(searchTerm)  
                var searchTermExpression = Expression.Constant(searchTerm);  
                var containsExpression = BuildContainsExpression(stringProperty, searchTermExpression);  
    
                orExpression = BuildOrExpression(orExpression, containsExpression);  
            }  
    
            var completeExpression = Expression.Lambda>(orExpression, stringProperty.Parameters);  
            return source.Where(completeExpression);  
        }  
    
        private static Expression BuildOrExpression(Expression existingExpression, Expression expressionToAdd)  
        {  
            if (existingExpression == null)  
            {  
                return expressionToAdd;  
            }  
    
            //Build 'OR' expression for each property  
            return Expression.OrElse(existingExpression, expressionToAdd);  
        }  
    }
    

    Alternatively, take a look at the github project for NinjaNye.SearchExtensions as this has other options and has been refactored somewhat to allow other combinations

提交回复
热议问题