2

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?

2 Answers 2

2

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));
Sign up to request clarification or add additional context in comments.

1 Comment

@Nilesh - you are welcome :) please consider marking question as solved and upvoting :)
0

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));
}

1 Comment

Have you checked that it compiles?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.