using System.Collections.Generic;
using System.Linq.Expressions;
public static void Main()
Console.WriteLine("Hello World");
List<User> userCollection = new List<User>() {
new User { Id = 1, Name = "Bob", Age = 2 },
new User { Id = 2, Name = "Dave", Age = 30 },
new User { Id = 3, Name = "Jane", Age = 42 },
new User { Id = 4, Name = "Anne", Age = 12 }
List<KeyValue> list = ReadCollection(userCollection, "Id", "Name");
Console.WriteLine("{0}: {1}", x.Key, x.Value);
private static List<KeyValue> ReadCollection<T>(IList<T> collection, string keyName, string valueName)
List<KeyValue> list = new List<KeyValue>();
Func<T, int> keyFunction = GenerateLambda<T, int>(keyName);
Func<T, string> valueFunction = GenerateLambda<T, string>(valueName);
for (int i = 0; i < collection.Count; i++)
int key = keyFunction(elem);
string value = valueFunction(elem);
list.Add(new KeyValue(key, value));
private static Func<T, TProp> GenerateLambda<T, TProp>(string propertyName)
var p = Expression.Parameter(typeof(T));
var expr = Expression.Lambda<Func<T, TProp>>(Expression.PropertyOrField(p, propertyName), p);
public int Id { get; set; }
public string Name { get; set; }
public short Age { get; set; }
public class UserCollection: List<User> {
public int Key {get; private set;}
public string Value {get; private set;}
public KeyValue(int key, string value)