I have a dynamic query that brings me dynamic columns (System.Linq.Dynamic.Core
):
var data = data.Select("new (col1, col2, col3)", "T", StringComparison.OrdinalIgnoreCase);
[
{ col1: "This", col2: 1.56, col3: "Something else" }
]
Now I need to bring the type of each column. ex:
[
{
col1: { value: "This", type: "string" },
col2: { value: 1.56, type: "decimal" }
}
]
To get that, I was thinking of something like:
var rows = data.Select(x => new {
Type = MyHelper.GetType(x),
Value = x
});
But that it's not working.
An unhandled error occurred The best overloaded method match for 'MyHelper.GetType(System.Reflection.PropertyInfo)' has some invalid arguments
I do know how to get the type
public static string GetType(PropertyInfo type)
{
return type.PropertyType.IsGenericType && type.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? type.PropertyType.GetGenericArguments()[0].ToString().Replace("System.", "") : type.PropertyType.Name;
}
But I don't know how to build the query.
[UPDATE]
This is a try, but not what I need
var rows = data.Select(x => new {
Type = MyHelper.GetType(x.GetType()),
Value = x
});
[
{
"type": "<>f__AnonymousType0`3",
"value": {
"col1": "2019-10-15T00:00:00",
"col2": 0.00,
"col3": "abc"
}
},
]
Here is a working demo you could refer to:
public List<object> Get(int id)
{
var data = new List<Object>
{
new{
col1="aaa",
col2= 1.25,
col3 = 1
},
new{
col2="asd",
col3= 1.2,
col4 =2
}
};
var aaa = new List<object>() { };
foreach (var item in data)
{
var ds = item.GetType().GetProperties();
foreach(var i in ds)
{
var name = i.Name;
var type = i.PropertyType.Name;
var value = item.GetType().GetProperty(name).GetValue(item);
aaa.Add(new { name=name, type = type, value = value });
}
}
return aaa;
}