Is this what you are after?
class Foo {
public string Property1 { get; set; }
public string Property2 { get; set; }
}
Func<Foo, object> lambda = foo => new { foo.Property1, foo.Property 2 };
var foo = new Foo { Property1 = "foo", Property2 = "bar" };
var anon = lambda(foo);
If so, and especially since you are talking about entities, I would suggest that you:
- Use
Tuple instead of anonymous types. Tuples are also immutable, which is a plus when you want to use them as dictionary keys.
- Integrate the unique key creation function in your entity class instead of spinning it out into an external function (anonymous or not). It's your entity that should know which of its properties make up a unique key, not some external code.
For example:
class Foo {
public string Property1 { get; set; }
public string Property2 { get; set; }
public object GetUniqueKey()
{
return Tuple.Create(this.Property1, this.Property2);
}
}
There's still an issue with the code above: Property1 and Property2 are publicly settable, which means that after you put Foo instances in a map their keys might not match their values if e.g. Property1 is later modified. However this is a problem that occurs quite often in practice and there's really no good solution that I know of other than "just don't mess with the object properties then".