I am using Dynamic Linq Library (System.Linq.Dynamic.dll
) for dynamic data retrieval, But I am facing some problem in converting the below code to dynamic linq.
Consider I have following class A
public class A
{
public int Id { get; set; }
public string Name { get; set; }
public int Data { get; set; }
}
And the following linq code also :
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();
}
How can I achieve the same using Dynamic Linq library?
Below is the dynamic code I have tried.
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();
But when I run the code I am getting the following exception
Unable to cast the type '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]]
'
to type 'System.Linq.IQueryable`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
'.LINQ to Entities only supports casting EDM primitive or enumeration types.