简体   繁体   English

动态值的 Linq 查询

[英]Linq query for dynamically value

I have an IQueryable collection of Employee objects which has FirstName , LastName , Department in it.我有一个IQueryableEmployee对象集合,其中包含FirstNameLastNameDepartment I'm passing a string of LastName separated by comma.我正在传递以逗号分隔的LastName字符串。 I want to use where clause to filter data which has LastName selected as "Sharma,Gupta" .我想使用where子句来过滤LastName选择为"Sharma,Gupta" Can someone help me out?有人可以帮我吗?

Employee class员工班

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Department { get; set; }
    public string EmpID { get; set; }
}

public IQueryable<Employee> GetEmpData(String filterExpression)
{
    IQueryable<Employee> data = GetEmployeeData();
    data = from da in data
           where (da.LastName == "Sharma")
           select da;
    return data;

}

In the above method I can query a single value.在上述方法中,我可以查询单个值。 filterExpression contains list of LastName separated by a comma. filterExpression包含以逗号分隔的LastName列表。 Can someone guide me how to use filterExpression in where clause?有人可以指导我如何在where子句中使用filterExpression吗?

Split your string and use .Contains :拆分您的字符串并使用.Contains

names = filterExpression.Split(",");
IQueryable<Employee> data = GetEmployeeData();
data = from da in data
       where names.Contains(da.LastName)
       select da;

As you return the entire object and do not project only parts of it using the method syntax might be more readable:当您返回整个对象并且不使用方法语法仅投影它的一部分时,可能更具可读性:

return GetEmployeeData().Where(item => names.Contains(item.LastName));

If your filterExpression is a string, with the names separated by commas, then you'd want to change your query to check if the last name is in the list of names in filterExpression like this:如果您的 filterExpression 是一个字符串,名称以逗号分隔,那么您需要更改查询以检查姓氏是否在 filterExpression 中的名称列表中,如下所示:

public IQueryable<Employee> GetEmpData(String filterExpression)
{
    List<string> names = filterExpression.Split(",");
    return GetEmployeeData().Where(names.Contains(da.LastName));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM