2

This is the scenario. I have the following three classes, they are defined in Entity Framework, i only define them here for the example:

public class Foo
{
  public string Color { get; set; }
}

public class Bar : Foo
{
  public string Height { get; set; }
}

public class Pipe : Foo
{
  public string Width { get; set; }
}

So, I have many Foo's, this is my base class, I want to be able to specify a propery, and do this query:

   from e in Context.Foos
   group e.Color by e.Color into result
   select new
   {
 Value      = result.Key,
 ValueCount = result.Count()
   }

This should end up with:

Blue 2 Black 4 Yellow 2

This works, however I want to specify this at run time, with the Property name 'Color' passed by the client. Also, I want to search the derived entities too. If i try to do

   group e.Height by e.Height into result

It wont work because there is no Height in Foo, only in Bar. But the point is I ONLY want to return Bars, this should also be specified at runtime. This is the main problem I have been having. I cant do Foos.OfType<Bar>.GroupBy(some dynamic stuff) because I dont know the type to filter for at runtime.

Would really appreciate some help on this matter.

EDIT

Basically, what i'm trying to do is this System.LINQ.Dynamic: Select(" new (...)") into a List<T> (or any other enumerable collection of <T>) but return Count instead of Sum at the end.

Community
  • 1
  • 1
James
  • 2,458
  • 3
  • 26
  • 50

1 Answers1

1

In this answer, a func is being used to create a dynamic Where.

private List<T> GetResults<T>(IQueryable<T> source, 
   Expression<Func<T, bool>> queryFunction)
{
   return source.Where(queryFunction).ToList<T>();
}

You should be able to do something similar with GroupBy.

Community
  • 1
  • 1
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • this will not work because you have to pass in a fully typed Func. However here I do not know the type of the object to search by until runtime. – James Jan 12 '10 at 10:28
  • You get to decide *which* fully typed function to pass in at runtime. – Robert Harvey Jan 12 '10 at 16:08