How to convert dynamic list to <dynamic> list
I have a swimlaneAttribute variable:
List<dynamic> swimlaneAttributes = new List<dynamic>();
but in the function i have the return type of the dynamic
public dynamic GetSwimlaneAttribute(List<ProjectSwimlaneAttribute> swimlaneAttributeTable, Dictionary<string, string> dic)
{
dynamic swimlaneAttributes = null;
swimlaneAttributes = swimlaneAttributeTable.Select(s => new
{
ID = s.Id,
DataType = s.AttributeDataType,
IsCriticalField = s.IsCriticalField,
});
return swimlaneAttributes;
}
this will return some records from the table parameter i am passing !!
now i have to call this function GetSwimlaneAttribute
, instead i will get all the required records (from the table) but when i pass this to swimlaneAttributes
it goes to the catch block !!!
swimlaneAttributes = GetSwimlaneAttribute();
if i pass it this way (i think the number of records will be 0)
//swimalneAttributes = GetSwimlaneAttribute as List<dynamic>;
So how to convert Dynamic to List
Thank!
source to share
You are currently returning a sequence of objects of an anonymous type. This sequence cannot be carried over to List<T>
, because it is not List<T>
.
You can change your ad to:
IEnumerable<dynamic> GetSwimlaneAttribute(...)
without changing the body of the code - then to get it List<dynamic>
, just call it like:
List<dynamic> list = GetSwimlaneAttribute(...).ToList();
If you absolutely cannot change the declaration, you can convert it outside of the method:
IEnumerable<dynamic> sequence = GetSwimlaneAttribute(...);
List<dynamic> list = sequence.ToList();
Or call the extension method directly:
List<dynamic> list = Enumerable.ToList<dynamic>(GetSwimlaneAttirbute(...));
However, you should be aware that anonymous types do not cross assembly boundaries (no hacking). You should strongly consider creating a named type for this.
Also, the body of your method is a little cool - you declare a variable and assign a null value to it, then immediately assign a different value, and then just return that value. All this can be written like this:
return swimlaneAttributeTable.Select(s => new
{
ID = s.Id,
DataType = s.AttributeDataType,
IsCriticalField = s.IsCriticalField,
});
source to share
why don't you try?
public List<dynamic> GetSwimlaneAttribute(List<ProjectSwimlaneAttribute> swimlaneAttributeTable, Dictionary<string, string> dic)
{
List<dynamic> swimlaneAttributes = new List<dynamic>(); // modified dynamic to List<dynamic>
swimlaneAttributes = swimlaneAttributeTable.Select(s => new
{
ID = s.Id,
DataType = s.AttributeDataType,
IsCriticalField = s.IsCriticalField,
});
return swimlaneAttributes;
}
source to share