在子集合上也设置 PredicateBuilder

Set PredicateBuilder also on child collection

我试图将谓词不仅应用于实体父集合,还应用于子集合。以下是我的部分代码:

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; }
}

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));