Reputation: 362
i have a variable swimlaneAttribute:
List<dynamic> swimlaneAttributes = new List<dynamic>();
but in a function i have a return type of 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 table parameter that i am passing!!
now i have to call this GetSwimlaneAttribute
function, in return i will get all the required records(from a table)
but when i pass this to swimlaneAttributes
it goes to catch block!!!
swimlaneAttributes = GetSwimlaneAttribute();
if i pass it this way, (i think the record count becomes 0)
//swimalneAttributes = GetSwimlaneAttribute as List<dynamic>;
So how to convert Dynamic to List
Thanks!
Upvotes: 6
Views: 30218
Reputation: 520
why don't you try this way?
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;
}
Upvotes: 0
Reputation: 1502806
You're currently returning a sequence of anonymous type objects. That sequence can't be cast to a List<T>
because it isn't a List<T>
.
You could change the declaration to:
IEnumerable<dynamic> GetSwimlaneAttribute(...)
with no change to the body of the code - then to get a List<dynamic>
just call it as:
List<dynamic> list = GetSwimlaneAttribute(...).ToList();
If you absolutely can't change the declaration, you could convert it outside 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 don't cross assembly boundaries (without a bit of hackery). You should strongly consider creating a named type for this instead.
Additionally, your method body is a bit crufty - you declare a variable and assign it a null value, then immediately assign a different value, and then just return that value. The whole thing could be written as:
return swimlaneAttributeTable.Select(s => new
{
ID = s.Id,
DataType = s.AttributeDataType,
IsCriticalField = s.IsCriticalField,
});
Upvotes: 5
Reputation: 520
How about this one?
List<dynamic> lstDynamic = new List<dynamic>();
lstDynamic.Add(GetSwimlaneAttribute());
and use lstDynamic.
Upvotes: 1