如何使用 LINQ 和 PredicateBuilder 构建使用子类的谓词?
How to use LINQ and PredicateBuilder to build a predicate using a subclass?
我正在尝试使用此答案将 OR 运算符动态添加到 LINQ 中的 WHERE 子句:
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,而不是 属性,我想做这样的事情:
searchPredicate.Or(SongsVar => SongsVar.Tags.Any().TagName.Contains(closureVariable));
然后我想到了这样的方法,但是不行:
searchPredicate.Or(x => x.Tags.Where(p => p.TagName.Contains(closureVariable )).Count() > 0);
这可能吗?
是的,应该可以:
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());
Songs
和 Tag
定义为:
public class Songs {
public List<Tag> Tags { get; set; }
}
public class Tag {
public string TagName { get; set; }
}
然后,res
包含预期的 songs
中定义的前 3 条记录。
我正在尝试使用此答案将 OR 运算符动态添加到 LINQ 中的 WHERE 子句:
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
searchPredicate.Or(SongsVar => SongsVar.Tags.Any().TagName.Contains(closureVariable));
然后我想到了这样的方法,但是不行:
searchPredicate.Or(x => x.Tags.Where(p => p.TagName.Contains(closureVariable )).Count() > 0);
这可能吗?
是的,应该可以:
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());
Songs
和 Tag
定义为:
public class Songs {
public List<Tag> Tags { get; set; }
}
public class Tag {
public string TagName { get; set; }
}
然后,res
包含预期的 songs
中定义的前 3 条记录。