Reputation: 6780
OK,
This question has probably been answered before, but I'm not sure of how to word the Title.
I have a class that has methods which return many composite LINQ queries. Most of these queries form Anonymous Types in order to get the data I need. I found out that I'm not able to return an Anonymous Type from a method, so I've been creating sub classes and populating them in the "select new" part of the query.
Is there a better way of doing this? All of these methods return an IEnumerable of some kind and I really want to keep things extracted.
Thanks!
Upvotes: 0
Views: 261
Reputation: 5402
or you can use technic of dp in this post
// Useful? probably not.
private void foo()
{
var user = AnonCast(GetUserTuple(), new { Name = default(string), Badges = default(int) });
Console.WriteLine("Name: {0} Badges: {1}", user.Name, user.Badges);
}
object GetUserTuple()
{
return new { Name = "dp", Badges = 5 };
}
// Using the magic of Type Inference...
static T AnonCast<T>(object obj, T type)
{
return (T) obj;
}
Upvotes: 0
Reputation: 46873
You could explictly define the anonymous types you are using as classes, and instead return those classes.
Generally if you are writing a library for others to consume, explicitly defined classes are a best practice.
Upvotes: 1