简体   繁体   中英

Create Object from Anonymous Type

I'm using EntityFramework to a list of objects from the database and I'm using Anonymous Types to eventually return the right object. Because there are several functions that has to do this 'Anonymous type conversion' I want to extract this to functions.

I can create a function to create a dynamic but can't create a function that converts a dynamic in a specific type because if the function has a parameter that contains a dynamic, the return type is a dynamic type too.

This works:

  List<SomeObject> list = list
            .Select(i => GetAnonymousType(i))
            .Select(i => new SomeObject {Item1 = i.Item1, Item2 =i.Item2}).ToList();

This doesn't:

List<SomeObject> list = list
         .Select(i => GetAnonymousType(i))
         .Select(i => CreateSomeObjectFromDynamic(i)).ToList();

 private static SomeObject CreateSomeObjectFromDynamic(dynamic i)
 {
     return new SomeObject {Item1 = i.Item1, Item2 = i.Item2};
 }

See: https://dotnetfiddle.net/zLFlur

Is there a way I can use a function like: CreateSomeObjectFromDynamic to return the right type?

According to provided code at fiddle , your problem is not with CreateSomeObjectFromDynamic method, your problem is with GetAnonymousType method. This method returns dynamic and .NET cannot handle it. The compliler error says that:

Cannot implicitly convert type 'System.Collections.Generic.List< dynamic >' to 'System.Collections.Generic.List< SomeObject >'

Even changing query to

list = list
      .Select(i => CreateSomeObjectFromDynamic(GetAnonymousType(i)))
      .ToList();

will produce the same error. But, if you change return type of GetAnonymousType method to object as below:

private static object GetAnonymousType(SomeObject i)
{
    return new { Item1 = i.Item1, Item2 = i.Item2 };
}

your problem will be solved. But, this works in memory, I am not sure that it will successfully be translated into SQL if you try to use it with IQueryable for example. Also, I do not recomend using dynamic , even though it works after chaning return type to object your code does not seem right. If you make a bit effort, I am sure that you will find another way, for example using inheritance , generics and etc.

try this:

      list = list
     .Select(i => GetAnonymousType(i))
     .Select(i => CreateSomeObjectFromDynamic(i) as SomeObject).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM