2

Is this possible to create new {variable = x.something} and specify variable name dynamically? For example:

var name = "dynamicName"; 
var result = context.select(x=> new {name.ToString() = x.something })

In this way we would have a list where property name is dynamicName. So is this somehow possible?

Mert Akcakaya
  • 3,109
  • 2
  • 31
  • 42
kosnkov
  • 5,609
  • 13
  • 66
  • 107

3 Answers3

5

This is not possible with an anonymous type, because anonymous types are not dynamic. They must be completely defined at compile time. However, you could use a dynamic object like ExpandoObject:

var name = "dynamicName"; 
var result = context.Select(x =>
                            {
                                var exp = new ExpandoObject() as IDictionary<string, object>;
                                exp[name] = x.something;
                                return (dynamic)exp;
                            });
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • interesting approach, I just wonder how you could possibly use `result` in a sensible manner now, as it could technically be a collection of literally anything. Just some food for thought.... – Bazzz Mar 30 '12 at 09:13
  • 1
    “A lambda expression with a statement body cannot be converted to an expression tree” – kosnkov Mar 30 '12 at 09:14
  • @kosnkov, actually that would work with Linq to Objects, but I don't think there's a way to do that with Entity Framework – Thomas Levesque Mar 30 '12 at 09:32
1

Use a

    Dictionary<string,string> myDic 

Then

    myDic.Add(name.ToString(), x.something)
Mikey Mouse
  • 2,968
  • 2
  • 26
  • 44
  • 1
    +1 but I'd suggest `Dictionary` then. For the simple reason that `x.something` is not necessarily a string. – Bazzz Mar 30 '12 at 09:10
1

You can create anonymous type at runtime with Reflection.Emit but it is not very easy (http://www.codeproject.com/Articles/13337/Introduction-to-Creating-Dynamic-Types-with-Reflec). Usually it is better just to us dictonary, array or dynamic

Nikolay
  • 3,658
  • 1
  • 24
  • 25