diff --git a/System.Linq.Dynamic.Core.sln b/System.Linq.Dynamic.Core.sln index 2be909cd..afae1909 100644 --- a/System.Linq.Dynamic.Core.sln +++ b/System.Linq.Dynamic.Core.sln @@ -1054,6 +1054,10 @@ Global {D8368319-F370-4071-9411-A3DADB234330} = {7971CAEB-B9F2-416B-966D-2D697C4C1E62} {B01B327C-FC68-49B6-BDE3-A13D0C66DF5C} = {7971CAEB-B9F2-416B-966D-2D697C4C1E62} {7AFC2836-0F6E-4B0D-8BB3-13317A3B6616} = {8463ED7E-69FB-49AE-85CF-0791AFD98E38} + {8C5851B8-5C47-4229-AB55-D4252703598E} = {DBD7D9B6-FCC7-4650-91AF-E6457573A68F} + {912FBF24-3CAE-4A50-B5EA-E525B9FAEC90} = {8463ED7E-69FB-49AE-85CF-0791AFD98E38} + {FA01CE15-315A-499E-AFC2-955CA7EB45FF} = {DBD7D9B6-FCC7-4650-91AF-E6457573A68F} + {D5844AE4-53FA-4C8A-9D52-AD213FD0CA1E} = {8463ED7E-69FB-49AE-85CF-0791AFD98E38} {2DE2052F-0A50-40C7-B6FF-52B52386BF9A} = {122BC4FA-7563-4E35-9D17-077F16F1629F} {7A31366C-DD98-41A3-A0C1-A97068BD9658} = {BCA2A024-9032-4E56-A6C4-17A15D921728} EndGlobalSection diff --git a/src/System.Linq.Dynamic.Core/DynamicClassFactory.cs b/src/System.Linq.Dynamic.Core/DynamicClassFactory.cs index d4ce7065..0dc61889 100644 --- a/src/System.Linq.Dynamic.Core/DynamicClassFactory.cs +++ b/src/System.Linq.Dynamic.Core/DynamicClassFactory.cs @@ -176,6 +176,24 @@ public static Type CreateType(IList properties, bool createPara return type; } + /// + /// Create an instance of a based on a list of . + /// + /// The dynamic properties including the value you want to set in the generated instance. + /// Create a constructor with parameters. Default set to true. Note that for Linq-to-Database objects, this needs to be set to false. + /// Instance of a . + public static DynamicClass CreateInstance(IList dynamicPropertiesWithValue, bool createParameterCtor = true) + { + var type = CreateType(dynamicPropertiesWithValue.Cast().ToArray(), createParameterCtor); + var dynamicClass = (DynamicClass)Activator.CreateInstance(type)!; + foreach (var dynamicPropertyWithValue in dynamicPropertiesWithValue.Where(p => p.Value != null)) + { + dynamicClass.SetDynamicPropertyValue(dynamicPropertyWithValue.Name, dynamicPropertyWithValue.Value!); + } + + return dynamicClass; + } + private static Type EmitType(IList properties, bool createParameterCtor) { var typeIndex = Interlocked.Increment(ref _index);