我正在使用 Dynamic Linq Library (System.Linq.Dynamic.dll
)进行动态数据检索,但我在将下面的代码转换为动态linq时遇到了一些问题。
考虑我有以下A类
public class A
{
public int Id { get; set; }
public string Name { get; set; }
public int Data { get; set; }
}
以下linq代码也是:
static void Main(string[] args)
{
List<A> lst = new List<A>()
{
new A() { Id = 1, Name = "A", Data = 10 },
new A() { Id = 1, Name = "B", Data = 15 },
new A() { Id = 2, Name = "C", Data = 10 },
new A() { Id = 2, Name = "D", Data = 15 }
};
var d = lst.GroupBy(gp => gp.Id)
.Select(
sl =>
new
{
Data = sl.Select(
s =>
new
{
data = s.Data,
id = s.Id,
Name = s.Name
})
.Union(sl.Select(
sd =>
new
{
data = sl.Sum(s => s.Data),
id = sl.Key,
Name = ""
}))
})
.SelectMany(sl => sl.Data).ToList();
}
如何使用Dynamic Linq库实现相同目标?
以下是我尝试的动态代码。
var d = res.GroupBy(qry.GroupByColumn, "it").Select("it").Cast<IQueryable<object>>()
.Select(
sl =>
new
{
data = sl.Select(selectString)
.Union(sl.Select(
sd =>
new
{
data = sl.Select(
"new(Min(" + qry.GroupByColumn + ") as "
+ qry.GroupByColumn + "," + sumQry + ",1 as IsTotal)")
}))
}).ToList();
但是当我运行代码时,我得到以下异常
无法转换类型'System.Linq.IGrouping`2
[[System.String, mscorlib, Version=4.0, Culture=neutral, PublicKeyToken=b77a5c561934e089], [DynamicClass1, DynamicClasses, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]
“
输入'System.Linq.IQueryable`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
'。LINQ to Entities仅支持转换EDM原语或枚举类型。