简体   繁体   中英

Linq query for dynamically value

I have an IQueryable collection of Employee objects which has FirstName , LastName , Department in it. I'm passing a string of LastName separated by comma. I want to use where clause to filter data which has LastName selected as "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. Can someone guide me how to use filterExpression in where clause?

Split your string and use .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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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