c# - 如何在 linq where 子句中使用函数的返回值?

标签 c# linq

我正在尝试针对 EF 实体类型(人员)创建一般搜索查询。一般而言,搜索采用一个字符串,用逗号将其分割,然后搜索其各种属性包含所有关键字的人。

我有一个名为 getProperties(Person p) 的函数,它接受一个实体(由实体类型覆盖),并返回一个由各种相关属性组成的字符串,这些属性用分隔符连接在一起......例如:

John~Doe~Team A~Full Time

如果用户搜索“Team A, Full”对应于上述扁平实体的人,则应返回...但是,如果输入“John, Smith”,则不应返回。

我认为下面的看起来是对的,但它就是行不通......

public IEnumerable<Person> SearchPeople(string searchString)
{
    if (searchString == null || string.IsNullOrEmpty(searchString.Trim()))
        return base._objectSet.ToList();

    string[] SearchWords = searchString.Split(',').Select(s => s.Trim()).ToArray();

    return (from    person 
            in      base._objectSet 
            let     t = (getProperties(person)) 
            where   SearchWords.All(word => t.Contains(word)) 
            select  person).ToList();
}

getProperties 函数是:

public static string getProperties(Person p)
{
    string[] values = { p.Surname, p.GivenName, p.Team, p.Status };
    return values.Aggregate((x, y) => String.IsNullOrEmpty(y) ? x : string.Concat(x, "~", y));
}

有人看到我哪里出错了吗?

编辑

没有引发异常,但是当我单步执行代码时,当我到达 linq 时,它会进入托管查询的工作单元的 dispose 方法。很奇怪。

如果我更改它以便它搜索硬编码字符串,它会按预期工作:

var test = (from    person 
            in      base._objectSet 
            where   SearchWords.All(word => "John~Doe~Team A~Full Time".Contains(word))
            select person).ToList();

好吧,它的工作原理是它匹配我期望的查询,但由于它是静态的,它返回每个人的记录(很像 where(true) =P)

编辑第二个

更奇怪的是,如果我将结果存储到一个 var 中,然后返回带有断点的 var,执行永远不会遇到断点......这个 linq 就像一个黑洞......我可以进入它,但它永远不会让我回到我的 SearchPeople 方法......它只是处理上下文并忘记它。

编辑第三个

如果我不立即调用 ToString() 并查看调试器中的 linq 表达式,它会显示“Linq to Entities 无法识别方法 getProperties(Person)”,看起来它在默默地阻塞我的方法。 . 有什么方法可以使用我的方法而不会被 linq 阻塞?

最佳答案

您要返回一个列表?尝试将返回类型设为 List 或将 .ToList() 更改为 AsEnumerable()

public List<Person> SearchPeople(string searchString)
{
    if (searchString == null || string.IsNullOrEmpty(searchString.Trim()))
        return base._objectSet.ToList();

    string[] SearchWords = searchString.Split(',').Select(s => s.Trim()).ToArray();

    return (from    person 
            in      base._objectSet 
            let     t = (getProperties(person)) 
            where   SearchWords.All(word => t.Contains(word)) 
            select  person).ToList();
}

关于c# - 如何在 linq where 子句中使用函数的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13649814/

相关文章:

c# - 全部的 HtmlAgilityPack 子串按长度

c# - 千位分隔值到整数

c# - 使用 LINQ to SQL 获取连接结果

c# - 有什么简单的方法可以在linq中选择

c# - 当您在需要 Expression 的地方使用自定义方法时,如何创建 C# 编译错误?

c# - LINQ 按名称排序 ThenBy ChildrenCollection.Name

c# - 如何处理多个资源文件进行本地化?

具有属性的类实例化的 C# 到 VB.NET 语法转换

c# - 找不到 ExpressionVisitor.VisistMemberAcess

c# - LINQ 表达式。从范围引用的类型变量 'p',但未定义