Reputation: 2018
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.
Upvotes: 2
Views: 935
Reputation: 180788
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
.
Upvotes: 1