如何使用LINQ和PredicateBuilder使用子类构建谓词?

时间:2015-07-30 15:53:35

标签: c# linq predicatebuilder

我正在尝试使用此答案动态地将OR运算符添加到LINQ中的WHERE子句:https://stackoverflow.com/a/782350/1316683

var searchPredicate = PredicateBuilder.False<Songs>();

foreach(string str in strArray)
{
    var closureVariable = str;
    searchPredicate = 
     searchPredicate.Or(SongsVar => SongsVar.Tags.Contains(closureVariable));
}

var allSongMatches = db.Songs.Where(searchPredicate);

在我的情况下,Tags是一个List&lt; Tag&gt;,而不是属性,我想做这样的事情:

searchPredicate.Or(SongsVar => SongsVar.Tags.Any().TagName.Contains(closureVariable));

然后我想到了这样的东西,它不起作用:

searchPredicate.Or(x => x.Tags.Where(p => p.TagName.Contains(closureVariable )).Count() > 0);

这可能吗?

1 个答案:

答案 0 :(得分:1)

是的,应该可以:

  var searchPredicate = PredicateBuilder.False<Songs>();

  var strArray = new[] {"aa", "bb"};

  foreach (string str in strArray) {
    var closureVariable = str;
    searchPredicate =
     searchPredicate.Or(songsVar => songsVar.Tags.Any(tagVar => tagVar.TagName == closureVariable));
  }

  var songs = new List<Songs> {
    new Songs {Tags = new List<Tag> {new Tag {TagName = "aa"}}},
    new Songs {Tags = new List<Tag> {new Tag {TagName = "bb"}}},
    new Songs {Tags = new List<Tag> {new Tag {TagName = "aa"}, new Tag {TagName = "cc"}}},
    new Songs {Tags = new List<Tag> {new Tag {TagName = "cc"}, new Tag {TagName = "dd"}}}
  };

  var res = songs.Where(searchPredicate.Compile());

SongsTag定义为:

  public class Songs {
    public List<Tag> Tags { get; set; }
  }

  public class Tag {
    public string TagName { get; set; }
  }

然后,res包含songs中按预期定义的前3条记录。