25

Presently in LINQ, the following compiles and works just fine:

var listOfFoo = myData.Select(x => new FooModel{
     someProperty = x.prop1,
     someOtherProperty = x.prop2
});

public class FooModel{
     public string someProperty  { get; set; };
     public string someOtherProperty  { get; set; };
}

However, the past few versions of .NET/C# have expanded the role of dynamic objects such as the ExpandoObject and I am wondering if there is a way to basically do this:

var listOfFoo = myData.Select(x => new ExpandoObject{
     someProperty = x.prop1,
     someOtherProperty = x.prop2
});

Obviously, I have already tried the code above without success, but it seems like I am missing something.

1
  • Simple anonymous type projections are all you need here. Sep 14, 2021 at 14:13

3 Answers 3

46

You should be able to create a new anonymous object without any type declared:

var listOfFoo = myData.Select(x => new {
    someProperty = x.prop1,
    someOtherProperty = x.prop2
});
5
  • D'oh! Man I feel dumb. Yes, it was this easy. Can accept answer in 6 minutes. Thanks! Mar 21, 2013 at 18:14
  • 6
    @MatthewPatrickCashatt Note that there is nothing dynamic about the object. The object that is defined here is statically typed and even immutable as well. Now if that's suitable for your needs, that's great, but if you really wanted what you asked for in the question, then this isn't it.
    – Servy
    Mar 21, 2013 at 18:17
  • Thanks, @Servy. I appreciate your answer as well. What is confusing to me in regards to your comment, however, is that @d_r_w's approach still let's me add dynamic properties to the object. For example, foreach(dynamic item in listOfFoo{ item.someNewProperty = "bar" } works fine. What am I missing? Mar 21, 2013 at 18:31
  • @MatthewPatrickCashatt Just because it compiles doesn't mean it works. Using dynamic is essentially turning off the compiler (or most of it, anyway) so you're not going to get compile time errors even if the code is not going to work at all at runtime.
    – Servy
    Mar 21, 2013 at 18:38
  • As an additional note, by not using the dynamic keyword in your selection of said anonymous object, you can keep the type checking of your compiler, so when you're accessing someProperty or someOtherProperty, the compiler will verify all operations on it are conformant to the type of the property.
    – CassOnMars
    Mar 21, 2013 at 18:44
12

There is nothing preventing you from using Select to return a collection of ExpandoObject's, you just aren't properly constructing the ExpandoObject. Here's one way:

var listOfFoo = myData.Select(x =>
    {
        dynamic expando = new ExpandoObject();
        expando.someProperty = x.prop1;
        expando.someOtherProperty = x.prop2;
        return (ExpandoObject)expando;
    });
17
  • 3
    I don't think that will work without converting to an IEnumerable. Mar 21, 2013 at 18:21
  • @MystereMan Converting what to an IEnumerable?
    – Servy
    Mar 21, 2013 at 18:21
  • Converting the EF IQueryable (I assume it's not Linq to objects). I don't think the ExpandoObject code will be convertible to SQL, so it would likely generate an EF error. You would have to convert the results to IEnumerable to do it. Mar 21, 2013 at 18:38
  • @MystereMan What makes you think that myData is an IQueryable? There's nothing in the question that seems to indicate that to me. If it is indeed an IQueryable then yes, you'd need to add an AsEnumerable in there to run this on the client side.
    – Servy
    Mar 21, 2013 at 18:40
  • 1
    @Todd Yes, if you try to access the data as a property, it won't work, because the object doesn't have that property, it's just faking it when using dynamic. Like I said, if you access the data as data in a collection, which is what it is, then it will work just fine.
    – Servy
    Mar 2, 2017 at 15:34
0
using (var command = this._context.Database.GetDbConnection().CreateCommand())
        {
            command.CommandText = "select * from persons";
            command.CommandType = CommandType.Text;
            this._context.Database.OpenConnection();
            using (var result = command.ExecuteReader())
            {
                var lst = new List<object>();
                var lstColumns = new UserAccount().GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList();
                while (result.Read())
                {
                    var newObject = new object();
                    dynamic myobject = new ExpandoObject();
                    IDictionary<string, object> myUnderlyingObject = myobject;
                    for (var i = 0; i < result.FieldCount; i++)
                    {
                        var name = result.GetName(i);
                        var val = result.IsDBNull(i) ? null : result[i];
                        myUnderlyingObject.Add(name, val);
                    }
                    lst.Add(myUnderlyingObject);
                }
                return Ok(lst);
            }
        }
3
  • this is a very complicated solution to a very simple request that was asked and answered almost 10 years ago. To provide a new answer now you should include supportive arguments why this solution is superior to the other existing ones, but here you've gone back to first principals to do in 25 lines of code what you could have done in a single Linq expression? Sep 14, 2021 at 14:16
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Sep 14, 2021 at 14:24
  • This is a good starting point. Thank you. Dec 27, 2021 at 21:10

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.