c# - 按计算属性搜索对象列表

标签 c# linq list linq-to-entities where

这是我的类(class):

public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string FullName { get { return FirstName + " " + LastName; } }
}

这是我的 list :

var persons = new List<Person>();
persons.Add(...);
persons.Add(...);
etc.

如果我尝试通过“计算的”属性 FullName 搜索列表,如下所示:

return persons.Where(p => p.FullName.Contains("blah")) 

我收到以下错误:

System.NotSupportedException: The specified type member 'FullName' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

我该如何解决这个问题?

最佳答案

您不能在 IQueriable 谓词中使用计算属性。有两种方法可以实现这一点。

您可以在数据库中创建一个 View 并在那里创建计算的 FullName 列并将该列映射回您的数据实体。

其次,您可以将所有数据检索回客户端并在内存中过滤它们:

persons
  .ToList() // Execute this query and get results
  .Where(p => p.FullName.Contains("blah");

关于c# - 按计算属性搜索对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13651953/

相关文章:

c# - 如何使用 StructureMap (4.0) 将依赖项注入(inject)自定义属性? MVC5项目

c# - 将结构数组从 C++ 转换为 C# 时出现问题

c# - 如何使用 LINQ 返回 FileInfo.Name 的子字符串

list - 为什么要使用两个堆栈进行排队?

python - 在没有设置的情况下更快地获得两个列表的差异

c# - 如何通过 Windows 服务使用 Windows Communication Foundation (WCF)

c# - 确定对象的类型并强制转换为类型

c# - 索引器属性的 Linq 表达式

c# - Lambda 属性值选择器作为参数

python - 给定列表中的一个单词,我需要找到列表中所有下一个数值