tags:

views:

166

answers:

2

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!

+1  A: 

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.

Alan
Yes, I could do that. As I mentioned, most of these LINQ queries also involve JOINS, So in some sense, they are still composites.
Chris
A: 

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;
}
chaowman
I will give it a shot and let you know how it works out... Thanks for the help!
Chris