Soe
Soe

Reputation: 91

How to create anonymous type using lambda expression?

Can someone show me how to create following anonymous type with lambda expression?

p => new { p.Property1, p.Property2}

I'm really stuck at this and no where to found the solution. I've tried so many way but still cannot produce above expression dynamically. My intension is to use this to map unique keys to my POCOs. Any help would really appreicate.

Upvotes: 1

Views: 1863

Answers (2)

Tuomas Hietanen
Tuomas Hietanen

Reputation: 5341

    Func<object> ano1 = () => new { Property1 = 1, Property2 = 2 };
    Expression<Func<object>> ano2 = () => new { Property1 = 1, Property2 = 2 };

Upvotes: 0

Jon
Jon

Reputation: 437784

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:

  1. Use Tuple instead of anonymous types. Tuples are also immutable, which is a plus when you want to use them as dictionary keys.
  2. 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".

Upvotes: 4

Related Questions