TheGeekZn
TheGeekZn

Reputation: 3914

Convert object to a queryable

I used a modified version of this answer: How to dynamically create a class in C#? to create a dynamic object that represents a typed class.

public static object CreateNewObject(string[] columnNames)
{
    var myType = CompileResultType(columnNames);
    return Activator.CreateInstance(myType) as IQueryable;

}

Then in the main app:

var obj = MyTypeBuilder.CreateNewObject(rs.ColumnNames);

I need to somehow convert that to an IQueryable so I can do some Linq calls off it, such as .where(), .select() ect. Naturally, I am not currently able to because my app doesn't know what is exactly in that object, or what that object is.

So what I need is:

var obj = MyTypeBuilder.CreateNewObject(rs.ColumnNames);
List<obj> aListICanFill = new List<obj>();

..

aListICanFill.where(x => x.Equals("")).take(3);

I've blindly tried different casts, and even failed to try an iterate through the object - and now I'm completley stuck.

Is there any way to do this?

http://msdn.microsoft.com/en-us/library/bb882637.aspx seems to be something I should hook onto.
What my object looks like:

enter image description here

Upvotes: 2

Views: 3974

Answers (2)

Chris McKelt
Chris McKelt

Reputation: 1388

check out linq to objects

http://msdn.microsoft.com/en-us/library/bb397919.aspx

Hopefully your object contains an array?

Could you give a sample of how you want to query it? And also what CompileResultType does?

var myType = CompileResultType(columnNames); 

EDIT

For future reference - as suggested by Shane - OP is trying out - Dynamic Linq dynamiclinq.codeplex.com

Upvotes: 0

Shane
Shane

Reputation: 459

If you can use List<dynamic> you can use Where and Select IEnumerable<T> extension methods like below. This does not work with IQueryable because those methods require an Expression which cannot be dynamic.

using System;
using System.Collections.Generic;
using System.Linq;

namespace DynamicListTest
{
   internal class Program
   {
      private static void Main(string[] args)
      {
         var dynamicObjects = GetDynamicObjects().Cast<dynamic>().AsEnumerable();

         var itemsToPrint = dynamicObjects
            .Where(item => item.Age > 30);

         foreach (var item in itemsToPrint)
         {
            Console.WriteLine(item);
         }

         Console.ReadKey();
      }

      private static IQueryable GetDynamicObjects()
      {
         return new List<dynamic>()
         {
            new { Name = "A", Age = 10 },
            new { Name = "B", Age = 20 },
            new { Name = "C", Age = 30 },
            new { Name = "D", Age = 40 },
            new { Name = "E", Age = 50 },
         }.AsQueryable();
      }
   }
}

This prints

{ Name = D, Age = 40 }

{ Name = E, Age = 50 }

Upvotes: 2

Related Questions