question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Anonymous object creation

See original GitHub issue

how to get from:

string strExpression = "x => new { x.Ido, x.OtdName }";

such expression:

Expression<Func<T, object>> result = x => new {x.Ido, x.OtdName };

I need this to select specific fields in Generic Repository:

public async Task<List<object>> GetList1(Expression<Func<T, object>> selectFields)
        {
            IQueryable<T> query = _dbSet;
            IQueryable<object> result;
         
            result = query.Select(selectFields);

            return await result.AsNoTracking().ToListAsync();
        }

Issue Analytics

  • State:open
  • Created 6 years ago
  • Comments:5 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
metoulecommented, Jun 8, 2021

I had a look, and it seems quite difficult: the anonymous type has to be defined at runtime, and to do that, you need to add a custom dynamic assembly to the current app domain, and then add the new anonymous type to that custom assembly. Also, that custom assembly must be unloaded when it’s no longer needed, to avoid memory bloat. Also, the anonymous type must define fields, properties, a default constructor, and possibly a ToString() method, otherwise it might not be understood by Entity Framework.

Creating a dynamic assembly doesn’t seem possible with netstandard 2.0, only with netstandard 2.1.

I found a project that does most of it, except that it doesn’t unload the dynamic assembly, and it’s also not compatible with netstandard.

https://github.com/dotlattice/LatticeUtils/blob/master/LatticeUtils/AnonymousTypeUtils.cs

0reactions
holdenmaicommented, Sep 19, 2022

Another possibility, depending on the outcome desired for this, is to return an ExpandoObject. This would allow consuming code to be able to reference it as dynamic, or be passed to other interpreters since there is already some support for

I do have a decent amount of experience in building classes at run time, especially for the simple classes that are created as anonymous types. Looking into how those are actually compiled out

var o = new { Prop1 = int.MaxValue, Prop2 = string.Empty };

ends up getting compiled out to a class as follows

public class <>f__AnonymousType0`2<Prop1, Prop2>
{
   private readonly Prop1<Prop1>i__Field;
   private readonly Prop2 <Prop2>i__Field;

    public <>f__AnonymousType0`2(Prop1 Prop1, Prop2 Prop2)
    {
        <Prop1>i__Field = Prop1;
        <Prop2>i__Field = Prop2;
    }
    
    public int Prop1 { get => <Prop1>i__Field; }
    public string Prop2 { get => <Prop2>i__Field; }

    public override string ToString()
    {
//Technically calls ToString() with a null check, but this shows the string format.
          return $"{{ Prop1: {Prop1}, Prop2: {Prop2} }}"
    }

    //Had to use ILDisassembler to get here.
    public override bool Equals(object o)
    {
        return o is <>f__AnonymousType0`2<Prop1, Prop2> a && EqualityComparer<Prop1>.Default.Equals(a.Prop1, Prop1) && EqualityComparer<Prop2>.Default.Equals(a.;
    }
    public override int GetHashCode()
    {
        //This is pretty ugly.  Having a hard time decompiling from MSIL in my head at the moment.
//Long story short, combines hash codes with the results from EqualityComparer<T>.Default
    }
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Anonymous Types
You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, ...
Read more >
Anonymous object in Java
Anonymous object in Java means creating an object without any reference variable. Generally, when creating an object in Java, ...
Read more >
C# Anonymous Types
You create an anonymous type using the new operator with an object initializer syntax. The implicitly typed variable- var is used to hold ......
Read more >
What is the Java equivalent of creating an anonymous ...
Normally anonymous classes are used to create implementations of interfaces and abstract classes and so are referenced using the interface or ...
Read more >
Anonymous object in Java
An anonymous object simplifies code structure by eliminating the need for explicit object creation. It is especially useful for one-time operation where ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found