如何编写通用LINQ查询,以便根据名字中间名和姓氏过滤数据

时间:2017-12-19 05:11:52

标签: entity-framework linq

我有一张表,其中包含员工记录,如姓,中,姓。我有3个文本框用于输入所有这些。 现在在.net端我想编写一个LINQ查询来根据first name middle name and last name过滤数据。这3个字段中的任何一个都可以为空白。 这些是编写单个通用LINQ查询的任何方式吗?

4 个答案:

答案 0 :(得分:4)

public IList<Employee> GetEmployees(string first, string middle, string last)
{
    var query = context.Employees.AsQueryable();
    if (!string.IsNullOrWhiteSpace(first))
    {
        query = query.Where(x => x.FirstName == first);
    }
    if (!string.IsNullOrWhiteSpace(middle))
    {
        query = query.Where(x => x.MiddleName == middle);
    }
    if (!string.IsNullOrWhiteSpace(last))
    {
        query = query.Where(x => x.LastName == last);
    }

    return query.Select(x => 
                    new Employee 
                    { 
                        FullName = string.Join(" ", new string[] { x.FirstName, x.MiddleName, x.LastName}.Where(y => !string.IsNullOrWhiteSpace(y)))
                    })
                .ToList();
}

答案 1 :(得分:0)

您可以使用或者像bellow

这样的条件编写一个linq查询
  

_context.tablename.where(p =&gt; p.firstName.contains(txtFirstName)|| p.middleName.contains(txtMiddleName)|| p.lastName.contains(txtLastName))。ToList();

使用上面的linq查询

中的数据库表更改tablename

答案 2 :(得分:0)

迭代时只需验证使用的条件是否具有值

var criteria = new 
{
    FirstName = default(string),
    MiddleName = default(string),
    LastName = "Doe",
};

var query = from record in Context()
            where !string.IsNullOrEmpty(criteria.FirstName) 
                    && record.FirstName == criteria.FirstName
                || !string.IsNullOrEmpty(criteria.MiddleName) 
                    && record.MiddleName == criteria.MiddleName
                || !string.IsNullOrEmpty(criteria.LastName) 
                    && record.LastName == criteria.LastName
            select record;

答案 3 :(得分:0)

尝试类似的东西;

    public List<Employee> RetrieveEmployees(string firstName, string lastName, string middleName)
    {
        var query = from employees in context.Employees
            where (string.IsNullOrEmpty(firstName) || employees.FirstName == firstName) &&
                  (string.IsNullOrEmpty(lastName) || employees.LastName == lastName) &&
                  (string.IsNullOrEmpty(middleName) || employees.MiddleName == middleName)
        select employees;

        return query.ToList();
    }