这就是场景。我有以下三个类,它们在Entity Framework中定义,我只在这里为它们定义它们:
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; }
}
所以,我有很多Foo,这是我的基类,我希望能够指定一个属性,并执行此查询:
from e in Context.Foos
group e.Color by e.Color into result
select new
{
Value = result.Key,
ValueCount = result.Count()
}
这最终应该是:
蓝色2 黑4 黄2
这有效,但是我想在运行时指定它,客户端传递属性名称'Color'。另外,我也想搜索派生实体。如果我试着做
group e.Height by e.Height into result
它无法工作,因为Foo中没有高度,只有在Bar中。但重点是我 ONLY 想要返回Bars,这也应该在运行时指定。这是我一直遇到的主要问题。我不能Foos.OfType<Bar>.GroupBy(some dynamic stuff)
,因为我不知道在运行时要过滤的类型。
非常感谢你对此事的一些帮助。
修改
基本上,我要做的就是这个System.LINQ.Dynamic: Select(" new (...)") into a List<T> (or any other enumerable collection of <T>),但最后会返回Count而不是Sum。
答案 0 :(得分:1)
在this answer中,func
用于创建动态Where
。
private List<T> GetResults<T>(IQueryable<T> source,
Expression<Func<T, bool>> queryFunction)
{
return source.Where(queryFunction).ToList<T>();
}
您应该可以使用GroupBy
执行类似操作。