Last active
May 30, 2020 12:16
-
-
Save afreeland/6730973 to your computer and use it in GitHub Desktop.
C#: Create an Expression to use with LINQ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public ActionResult Grid(string FirstName, string LastName) | |
{ | |
GridHelper.Filters filter = new GridHelper.Filters("FirstName", "LastName"); | |
var _page =(!String.IsNullOrEmpty(HttpContext.Request.QueryString["page"])) ? Convert.ToInt32(HttpContext.Request.QueryString["page"]) : 1; | |
var _contacts = from c in testDB.Contacts | |
join ac in testDB.Account_Contact on c.ID equals ac.ContactID | |
where ac.AccountID == 725 | |
select c; | |
// Create the parameter (typically the 'x' in your expression (x => 'x') | |
ParameterExpression param = Expression.Parameter(typeof(Contact), "parm"); | |
// Store the result of a calculated Expression | |
Expression exp = null; | |
if (!String.IsNullOrEmpty(filter.List["FirstName"])) | |
{ | |
// The member you want to evaluate (x => x.FirstName) | |
MemberExpression member = Expression.Property(param, "FirstName"); | |
// The method you want to use to create an 'IN' statement | |
MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) }); | |
// The value you want to evaluate | |
ConstantExpression constant = Expression.Constant(filter.List["FirstName"]); | |
//BinaryExpression result = Expression.Equal(member, constant); | |
// Actually apply the expression together (x => x.FirstName.Contains('value')) | |
MethodCallExpression result = Expression.Call(member, method, constant); | |
// The Result | |
exp = result; | |
// Creates the expression against the type | |
Expression<Func<Contact, bool>> deleg = Expression.Lambda<Func<Contact, bool>>(exp, param); | |
// Apply our newly created expression against the .Where clause | |
_contacts = _contacts.Where(deleg); | |
} | |
ViewBag.Data = _contacts.ToList(); | |
return View(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment