Is there a way to convert a dynamic or anonymous object to a strongly typed, declared object?

前端 未结 4 1049
轻奢々
轻奢々 2020-12-17 07:45

If I have a dynamic object, or anonymous object for that matter, whose structure exactly matches that of a strongly typed object, is there a .NET method to build a typed obj

4条回答
  •  半阙折子戏
    2020-12-17 08:05

    Here we can convert an anonymous object to Dictionary

    Dictionary dict = 
        obj.GetType()
          .GetProperties()
          .ToDictionary(p => p.Name,  p => p.GetValue(obj, null));
    

    Also you can cast an object using LINQ:

    List items = anonymousType.Select(t => new MyType(t.Some, t.Other)).ToList();
    

提交回复
热议问题