How to dynamically add OR operator to WHERE clause in LINQ

后端 未结 4 796
花落未央
花落未央 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:54

    You can use the PredicateBuilder class:

    var searchPredicate = PredicateBuilder.False();
    
    foreach(string str in strArray)
    {
       var closureVariable = str; // See the link below for the reason
       searchPredicate = 
         searchPredicate.Or(SongsVar => SongsVar.Tags.Contains(closureVariable));
    }
    
    var allSongMatches = db.Songs.Where(searchPredicate);
    

    LinqToSql strange behaviour

提交回复
热议问题