Use Linq.Dynamic or Expressions to create an new anonymous object

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Use Linq.Dynamic or Expressions to create an new anonymous object



I've the following code:


public class C

public string Field get; set;
public string Data get; set;


var x = new C Field = "F", Data = "Data 1" ;
var y = new C Field = "G", Data = "Data 2" ;



And I want to cast this to an anonymous object like:


var x_a = new F = "Data 1" ;
var y_a = new G = "Data 2" ;



Note that the property name (F or G) is the content, so this can change dynamically. I'm currently using the System.Linq.Dynamic 'Select' method for this:


public static object CastToAnonymous(this C source)

var objects = new List<C>(new source).AsQueryable().Select("new (Data as " + source.Field + ")") as IEnumerable<object>;
return objects.First();




I'm wondering if there is an easier way to achieve this?





Besides the obligatory question why you want to do this (I really like to know), I don't think there's an easier way, since System.Linq.Dynamic already implements the expression parsing stuff for you, so your code is already a one-liner.
– sloth
Nov 2 '12 at 13:37


System.Linq.Dynamic





FYI, the objects you get from using Select() in the dynamic linq library are not compatible with the ones that the compiler generates. Does it really need to be a typed anonymous object? Why not just put it in a dynamic object? Use an expando object or write a dynamic wrapper.
– Jeff Mercado
Nov 2 '12 at 14:22



Select()





Why do you want to cast it to anonymous type with same fields? What do you want to do with it then?
– Kirill Bestemyanov
Nov 2 '12 at 14:46





FYI, Technically this is not a cast.
– andleer
Nov 2 '12 at 20:50





Couldn't you just place the values into a dictionary? You're making it harder than it needs to be IMHO.
– Jeff Mercado
Nov 4 '12 at 17:22









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard