it's possible to return, from a 开发者_运维技巧method, an anonymous type list?
I build my list of anonymous type like this
var l = (new[] { new { Name = "thename", Age = 30 } }).ToList();
Thanks
It is possible if you return list that was cast to object
, but it is useless. Consider creating class with corresponding fields instead of anonymous class.
It is possible, at a pinch, it's rather humourously called 'mumbling'.
This involves passing in a prototype of your anonymous type as a generic variable. Remembering that two anonymous types are considered to be the same type if they have the same named/typed properties in the same order.
- First usage by Wes Dyer (I believe).
- Eric Lippert on an answer to a question of which yours is probably a duplicate.
- Mentioned, with preferred alternatives by Dustin Campbell
I have write this method:
List<T> Cast<T>(object o, T type)
{
return (List<T>)o;
}
and the method that should return a anonymous type list, now return an object and I cast, with Cast<T>
method, to what I need.
It is a tricky method, but is does what I need for now.
thanks to all
From Creating a list of Anonymous Type in VB, a quote from JaredPar:
Here's a handy method for creating a list of an anonymous type from a single anonymous type.
Public Function CreateListFromSingle(Of T)(ByVal p1 As T) As List(Of T)
Dim list As New List(Of T)
list.Add(p1)
return List
End Function
Now you can just do the following
Dim list = CreateListFromSingle(dsResource)
There's some more discussion about the topic in the original post.
精彩评论