我正在尝试不仅将谓词应用于实体父对象,还将其应用于子集合。以下是我的代码的一部分:
var predicate = PredicateBuilder.New<Entity>();
foreach (string keyword in keywords)
{
string temp = keyword;
predicate = predicate.Or(p => p.Name.Equals(temp));
predicate = predicate.Or(p => p.Addresses.Select(x=> x.Name.Equals(temp));
}
第predicate = predicate.Or(p => p.Addresses.Select(x=> x.Name.Equals(temp));
行不起作用?有什么想法吗?
编辑
在下面的演示中,我要求获取名称为tom的实体父级和子级,但我也要获取名称为tom2的子级。
private static void Main(string[] args)
{
var result = GetAll(GetAll(), new List<string> { "tom" });
}
private static List<User> GetAll()
{
return new List<User>
{
new User
{
Id = 1,
Name = "tom",
Addesses = new List<Addesses>
{
new Addesses { Id = 1, Name = "tom" },
new Addesses { Id = 1, Name = "tom2" },
}
},
new User
{
Id = 1,
Name = "sam",
Addesses = new List<Addesses>
{
new Addesses { Id = 1, Name = "sam" },
new Addesses { Id = 1, Name = "sam2" },
}
},
};
}
private static List<User> GetAll(List<User> users, List<string> keywords)
{
var predicate = PredicateBuilder.New<User>();
foreach (string keyword in keywords)
{
string temp = keyword;
predicate = predicate.Or(p => p.Name.Equals(temp));
predicate = predicate.Or(p => p.Addesses.Any(x => x.Name.Equals(temp)));
}
var result = users
.Where(predicate)
.ToList();
return result;
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public List<Addesses> Addesses { get; set; }
}
public class Addesses
{
public int Id { get; set; }
public string Name { get; set; }
}
答案 0 :(得分:0)
对p.Addresses.Select(x=> x.Name.Equals(temp)
的调用未返回布尔结果。
根据您的实际逻辑,您可能需要研究Any
:
predicate = predicate.Or(p => p.Addresses.Any(x=> x.Name.Equals(temp));
或All
:
predicate = predicate.Or(p => p.Addresses.All(x=> x.Name.Equals(temp));