views:

104

answers:

1

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 http://stackoverflow.com/questions/1465700/system-linq-dynamic-select-new-into-a-listt-or-any-other-enumerable but return Count instead of Sum at the end.

+2  A: 

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.

Robert Harvey
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
You get to decide *which* fully typed function to pass in at runtime.
Robert Harvey