Jude
Jude

Reputation: 2433

How to get a variable replaced with a field name in a LINQ?

string companyName="ABC";
var query = from q in context.Company where q.CompanyName == companyName select q;

Is there any way to replace the q.CompanyName part of the query with a string variable so that the field used for filtering be a parametric?

I tried

string str1 = "companySize";
string str2 = "q." + str1; 
string companySize = "Mid";
var query = from q in context.Company where str2 == companySize select q; 

Didn't work. Been trying to let the user choose the columns for the query.

Upvotes: 1

Views: 90

Answers (3)

Pranay Rana
Pranay Rana

Reputation: 176886

Read more about both below option at : Dynamic query with Linq

you can use one of this

  1. Use Dynamic LINQ library

    Example for the the blog below

    string strWhere = string.Empty;
    string strOrderBy = string.Empty;
    
    if (!string.IsNullOrEmpty(txtAddress.Text))
        strWhere = "Address.StartsWith(\"" + txtAddress.Text + "\")"; 
    if (!string.IsNullOrEmpty(txtEmpId.Text))
    {
        if(!string.IsNullOrEmpty(strWhere ))
            strWhere = " And ";
        strWhere = "Id = " + txtEmpId.Text;
    }
    if (!string.IsNullOrEmpty(txtDesc.Text))
    {
        if (!string.IsNullOrEmpty(strWhere))
            strWhere = " And ";
        strWhere = "Desc.StartsWith(\"" + txtDesc.Text + "\")";
    }
    if (!string.IsNullOrEmpty(txtName.Text))
    {
        if (!string.IsNullOrEmpty(strWhere))
            strWhere = " And ";
        strWhere = "Name.StartsWith(\"" + txtName.Text + "\")";
    }
    
    EmployeeDataContext edb = new EmployeeDataContext();
    var emp = edb.Employees.Where(strWhere);
    
  2. Predicate Builder

EXample

    var predicate = PredicateBuilder.True<employee>();

    if(!string.IsNullOrEmpty(txtAddress.Text))
        predicate = predicate.And(e1 => e1.Address.Contains(txtAddress.Text));
    if (!string.IsNullOrEmpty(txtEmpId.Text))
        predicate = predicate.And(e1 => e1.Id == Convert.ToInt32(txtEmpId.Text));
    if (!string.IsNullOrEmpty(txtDesc.Text))
        predicate = predicate.And(e1 => e1.Desc.Contains(txtDesc.Text));
    if (!string.IsNullOrEmpty(txtName.Text))
        predicate = predicate.And(e1 => e1.Name.Contains(txtName.Text));

    EmployeeDataContext edb= new EmployeeDataContext();
    var emp = edb.Employees.Where(predicate);

Upvotes: 2

Hogan
Hogan

Reputation: 70513

I think the best way to do this is with built in libraries (and PropertyDescriptor type).

using System.ComponentModel;

void Main()
{
   Test test = new Test();
   test.CompanyName = "ABC";

   object z = TypeDescriptor.GetProperties(test).OfType<PropertyDescriptor>()
                  .Where(x => x.Name == "CompanyName").Select(x => x.GetValue(test)).FirstOrDefault();

   Console.WriteLine(z.ToString());
}

public class Test
{
   public string CompanyName { get; set; }
}

Upvotes: 1

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

If you don't want to use libraries like dynamicLINQ, you can just create the Expression Tree by yourself:

string str1 = "companySize";
string str2 = "q." + str1; 
string companySize = "Mid";

var param = Expression.Parameter(typeof(string));
var exp = Expression.Lambda<Func<Company, bool>>(
              Expression.Equal(
                  Expression.Property(param, str1),
                  Expression.Constant(companySize)),
              param);

var query = context.Company.Where(exp);

Upvotes: 1

Related Questions