如何从Linq语法转换为动态语法
本文关键字:语法 转换 动态 Linq | 更新日期: 2023-09-27 18:02:08
我使用的是System.Linq.Dynamic (http://msdn.microsoft.com/en-us/vstudio//bb894665.aspx)类。它用于定义动态Linq查询。我需要我的查询是动态的,这样它们就可以在运行时定义。
我将用一个例子来解释:有一个包含Transaction对象列表的Transactions对象。
public class Transactions : List<Transaction>
{
public Transactions() { }
public Transactions(List<Transaction> trans) : base(trans) { }
}
public class Transaction
{
public string Type;
public int Value;
}
假设我声明了Transactions对象并填充了一些数据:
Transactions trans = new Transactions
{
new Transaction {
Type = "A",
Value = 20,
},
new Transaction {
Type = "B",
Value = 34,
},
... and so on
};
我可以像这样运行Linq查询从trans中提取一些数据:
var mySum = from tran in trans
group tran by tran.Type into tranGroup
select new
{
Type = tranGroup.Key,
Total = tranGroup.Sum(s => s.Value)
};
可以(不那么容易)转录为以下动态查询
var mySum = trans
.AsQueryable()
.GroupBy("new(Type)", "new(Value)")
.Select("new(Key.Type as Type, Sum(Value) as Total)");
它所做的是给出一个对象,其中Type作为分组类型,Total作为特定组的sum Value。例如,它可能看起来像这样:
mySum = [{Type:"A", Total: 120},{Type:"B", Total: 200},{Type:"C", Total: 60}]
我了解动态查询的基本原理,但似乎没有任何复杂动态查询的清晰示例,包括对发生的事情的解释。
这是我不能解决的部分。给定以下Linq查询:
var myQuery = from tran in trans
group tran by tran.Type into tranGroup
select new
{
Type = (tranGroup.Key == "A" ? "Alfa" : (tranGroup.Key == "B" ? "Bravo" : (tranGroup.Key == "C" ? "Charlie" : (tranGroup.Key == "D" ? "Delta" : "")))),
Data = (from tranValue in tranGroup
select tranValue.Value).ToList()
};
最终会得到如下的结果:
myQuery = [{Type:"Alfa", Data: [50,60,10]},{Type:"Bravo", Data: [60,70,40,30]},{Type:"Charlie", Data: [10,30,5,15]}]
就是这样动态地写,但是没有嵌套:
var myQuery = trans
.AsQueryable()
.GroupBy("new(Type)", "new(Value)")
.Select(@"new((Key.Type == ""A"" ? ""Alfa"" : (Key.Type == ""B"" ? ""Bravo"" : (Key.Type == ""C"" ? ""Charlie"" : (Key.Type == ""D"" ? ""Delta"" : ""Other"")))) as Type, """" AS Data)");
我如何写上面的动态查询包括嵌套数组的值?
谁能给我指出一些好的例子的方向,或者给我一些例子,包括如何分组和求和?
我自己想出来的
问题是我在执行"new(Value) " "Value"在上面我应该只做"Value"。我看到了一个使用它作为参数的示例查询。基本上它表示当前项目。
这是一个Linq查询
var myQuery = from tran in trans
group tran by tran.Type into tranGroup
select new
{
Type = (tranGroup.Key == "A" ? "Alfa" : (tranGroup.Key == "B" ? "Bravo" : (tranGroup.Key == "C" ? "Charlie" : (tranGroup.Key == "D" ? "Delta" : "")))),
Data = (from tranValue in tranGroup
select tranValue.Value).ToList()
};
,可以转录成动态查询
var myQuery = trans
.AsQueryable()
.GroupBy("new(Type)", "Value")
.Select(@"new((Key.Type == ""A"" ? ""Alfa"" : (Key.Type == ""B"" ? ""Bravo"" : (Key.Type == ""C"" ? ""Charlie"" : (Key.Type == ""D"" ? ""Delta"" : ""Other"")))) as Type, it AS Data)");
返回的结果类似于
myQuery = [{Type:"Alfa", Data: [50,60,10]},{Type:"Bravo", Data: [60,70,40,30]},{Type:"Charlie", Data: [10,30,5,15]}]