0

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!

raven
  • 18,004
  • 16
  • 81
  • 112
Chris
  • 6,702
  • 8
  • 44
  • 60

2 Answers2

1

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
  • 45,915
  • 17
  • 113
  • 134
  • 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 Dec 16 '08 at 22:07
0

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;
}
Community
  • 1
  • 1