Skip to content

Instantly share code, notes, and snippets.

@AlexArchive
Created July 19, 2013 04:58
Show Gist options
  • Save AlexArchive/6035955 to your computer and use it in GitHub Desktop.
Save AlexArchive/6035955 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
namespace Code
{
public sealed class Program
{
static void Main(string[] args)
{
var people = new List<Person>()
{
new Person("Alex"),
new Person("Jamie"),
new Person("Daniel")
};
//declare a param "person" of type Person
var paramExpression = Expression.Parameter(typeof (Person), "person");
//perform member-access to get Person.Name
var membeExpression = Expression.PropertyOrField(paramExpression, "Name");
//define const string "Alex"
var constExpression = Expression.Constant("Alex", typeof (string));
//test the value of .Name against this constant
var binarExpression = Expression.Equal(membeExpression, constExpression);
//wrap the whole thing up in a lambda
var lambda = Expression.Lambda<Func<Person, bool>>(binarExpression, paramExpression);
var person = people.Where(lambda.Compile());
Debugger.Break();
}
}
public class Person
{
public string Name { get; set; }
public Person(string name)
{
Name = name;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment