In my project, I'm using Dynaic LINQ (https://dynamic-linq.net/) to select data from a database. Here's my current select code:
List<dynamic> clientData = await clientDataset
.Select($"new({string.Join(",", requiredColumns)})")
.ToDynamicListAsync();
I need to extend this. In a later step on the client side, I have to add additional properties to the clientData objects. As far as I know, this is not possible out of the box. The following approach doesn't work:
foreach (dynamic listEntry in clientData)
{
listEntry["MyAdditionalProp1"] = GetStringValue1();
listEntry["MyAdditionalProp2"] = GetStringValue2();
}
So I had the idea to add those as fake columns in the select statement, which doesn't work also.
List<dynamic> clientData = await clientDataset
.Select($"new({string.Join(",", requiredColumns)},'' AS MyAdditionalProp1, '' AS MyAdditionalProp2)")
.ToDynamicListAsync();
The names of the additional properties (MyAdditionalProp1, MyAdditionalProp1, ...) are known before the select, but they are dynamic, so I can't hard-code them.
How can I add dynamic properties to my list and modify their values atrwards like in the foreach loop?
CodePudding user response:
Assuming that Dynamic LINQ returns ExpandoObject
, you can do the following:
foreach (IDictionary<string, object> listEntry in clientData)
{
listEntry["MyAdditionalProp1"] = GetStringValue1();
listEntry["MyAdditionalProp2"] = GetStringValue2();
}
CodePudding user response:
Since Dynamic LINQ creates an anonymous type at runtime based on the string
new expression, you can't add properties to the object once created.
So you do need to add the properties to the new expression:
List<dynamic> clientData = await clientDataset
.Select($"new({string.Join(",", requiredColumns)},\"\" AS MyAdditionalProp1, \"\" AS MyAdditionalProp2)")
.ToDynamicListAsync();
Then, since you don't know the property names at runtime, you must use the helper functions provided by the library:
foreach (dynamic listEntry in clientData) {
listEntry.SetDynamicPropertyValue("MyAdditionalProp1", GetStringValue1());
listEntry.SetDynamicPropertyValue("MyAdditionalProp2", GetStringValue2());
}
And you can access the property values with GetDynamicPropertyValue()
.
NOTE: Extensive use of dynamic
can cause performance issues.