3

I have a class:

public class Person {
        public virtual string Id { get; set; }
        public virtual string Name { get; set; }
        public virtual int Age { get; set; }
        public virtual DateTime UpdateTime { get; set; }
}

And I have two Expression<Func<T, object>> objects:

Expression<Func<Person, object>> exp1 = t => t.UpdateTime
Expression<Func<Person, object>> exp2 = t => new {t.Age, t.Name}

And now I need to merge them to

Expression<Func<Person, object>> exp1 = t => new {t.UpdateTime, t.Age, t.Name}

Is this possible? If so, how?

Jonny.ZCH
  • 31
  • 2
  • [The question is already been answered do a research before asking a question](https://stackoverflow.com/questions/457316/combining-two-expressions-expressionfunct-bool) – Michael Apr 30 '21 at 10:11
  • 4
    @Thenighthunter in the question you point out, the accepted answer suggests to use `AndAlso` or `OrElse` because the predicate returns bool. OP is asking how to merge two objects. So how is this relevant here? – derloopkat Apr 30 '21 at 10:54
  • 1
    This question needs more details. While it is something that is definitely possible, `T` in the example is not valid (or rather does not contain enough information) since an arbitrary `T` can't possibly have the specified properties. Can you show perhaps a full method or class declaration? Is `T` constrained to something or was it perhaps a bad example and `T` is really meant to represent a specific claas? Can you show that definition? – pinkfloydx33 Apr 30 '21 at 11:03
  • 1
    In the general case, your problem is that you are creating a new class for the anonymous result, and that is difficult at runtime (and only worthwhile in very specific scenarios). What do you expect to be able to do with the return from the combined `Expression`? – NetMage Apr 30 '21 at 14:44
  • @pinkfloydx33 I've added more details in problem – Jonny.ZCH May 06 '21 at 01:26
  • Your input expressions contain anonymous types; `new {...}`. The C# compiler will generate these types and give them names. Your final expression would require you to define a new type. This is not something I'd want to try. However merging two `Expression>` would be much simpler and might meet your needs. https://stackoverflow.com/questions/55238121/how-to-merge-two-expressionfunct-t – Jeremy Lakeman May 06 '21 at 01:45
  • Alternatively, you could construct a string with the new properties for use with the [Dynamic LINQ library](https://dynamic-linq.net/). It has excellent facilities for constructing something like an anonymous type at runtime. – Zev Spitz Jun 03 '21 at 06:06

0 Answers0