Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Expression for Contains

I want to add dynamic expression in linq but facing issues on contains method it is working perfectly for Equal method

Problem is i'm getting FilterField dynamically how to replace in query

So far i had tried

List<int> Ids = new List<int>();  
**string filterField ="DEPARTMENT"; ==> Dynamic Field**

var eParam = Expression.Parameter(typeof(EmployeeDetail), "e");

var comparison = Expression.Equal(Expression.Property(eParam, filterField), Expression.Convert(Expression.Constant(Ids), Expression.Property(eParam, filterField).Type));

var lambda = Expression.Lambda<Func<EmployeeDetail, bool>>(comparison, eParam);

var countMonthly1 = ctx.tblMonthlyInput.Join(ctx.tblEmployee, a => a.CompanyId, b => b.CompanyId, (a, b) => b).Where(lambda).Count();

I want to make above query works for Contains method using linq expression

sample query :

var countMonthly = (from a in ctx.tblMonthlyInput
                    join b in ctx.tblEmployee on a.CompanyId equals b.CompanyId
                    where categoryId.Contains(a.CategoryId)  //want to make this dynamic
                    select a).Count() == 0;
like image 555
Nilesh Gajare Avatar asked Apr 11 '16 11:04

Nilesh Gajare


People also ask

How to check contains in linq?

The Linq Contains Method in C# is used to check whether a sequence or collection (i.e. data source) contains a specified element or not. If the data source contains the specified element, then it returns true else return false.

How contains work in linq?

LINQ Contains is quantifier operator. In LINQ Contains it also checks with the data sources, to check whether the collection of lists contains their desired element or not, and then it returns the result as either true or false based on the expected outcomes of the result.

What is LINQ expression?

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.


1 Answers

This will work for you:

void Main()
{
    var filterField = "Id";
    List<int> Ids = new List<int>();
    var eParam = Expression.Parameter(typeof(EmployeeDetail), "e");
    var method = Ids.GetType().GetMethod("Contains");
    var call = Expression.Call(Expression.Constant(Ids), method, Expression.Property(eParam, filterField));
    var lambda = Expression.Lambda<Func<EmployeeDetail, bool>>(call, eParam);
}

public class EmployeeDetail
{
    public int Id { get; set; }
}

First, you look for the Contains method on the type of Ids. Then we simply invoke it with Ids as the instance, and the property as the argument

like image 127
Rob Avatar answered Sep 18 '22 13:09

Rob