Anonymous type collection and casting

Hello Experts,

I create a function which returns an IQueryable or IEnumerable like this:
object MyFunction()
var result = from Categories in dataContext.Categories
                   where ...
                   select new {Type = "Category", CategoryId, CategoryName};
return result;

As you can see, I return an object because this is the only way I found.
But now, I need to cast this object or return the already casted IEnumerable or IQueryable object.

How can I do ?
I don't know how to cast to a generic list of anonymous type.
I do like this to create a generic list of anonymous type:
var anonymous = new {Type = "Category", CategoryId=0, CategoryName=""};
var list = (new []{anonymous}).ToList();
This is really strange to do something like this !!!

Thanks in advance for your help.
Who is Participating?
Göran AnderssonConnect With a Mentor Commented:
> I don't know how to cast to a generic list of anonymous type.

You can't do that. As the type is anonymous, there is no name that you can use to cast it.

Outside the scope where the anonymous type is created, the type is not know. As the type is anonymous, you don't have any name to use when casting it.

You simply can't return an anonymous type from a method without making the type unusable.

What is it that you are trying to accomplish, really? Can't you just declare a class that you can use in the return value?
class MyClass {
   public string Type { get; private set; }
   public int CategoryId { get; private set; }
   public string CategoryName { get; private set; }
   public MyClass (string type, int catId, string catName) {
      Type = type;
      CategoryId = catId;
      CategoryName = catName;
IEnumerable<MyClasss> MyFunction() {
return from Categories in dataContext.Categories
                   where ...
                   select new MyClass("Category", CategoryId, CategoryName);

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.