cuo*_*gle 5 c# linq dynamic-linq
假设我有一个DataTable三列C1, C2, C3:
var dt = new DataTable();
dt.Columns.Add("C1", typeof (int));
dt.Columns.Add("C2", typeof (string));
dt.Columns.Add("C3", typeof(string));
dt.Rows.Add(1, "1", "1");
dt.Rows.Add(1, "1", "2");
dt.Rows.Add(1, "2", "2");
我在 nuget to GroupBycolumns上使用 Dynamic Linq C1,就像C2下面的代码一样,它运行得很好:
 var output = dt.AsEnumerable()
            .AsQueryable()
            .GroupBy("new(it[\"C1\"] as C1, it[\"C2\"] as C2)", "it");
如果您注意到,有一个硬编码字符串 it呈现为DataRow,我从以下地方得到这个想法:
。例如,如果我尝试更改it为字符串:row
GroupBy("new(row[\"C1\"] as C1, row[\"C2\"] as C2)", "row");
我会得到运行时错误:
“DataRow”类型中不存在属性或字段“row”
所以,我不太清楚为什么必须硬编码 it为DataRow?这有什么原因吗。
这就是动态 LINQ 提供程序的编写方式。它具有在尝试解析 LINQ 表达式时识别的三个硬编码关键字:it、iff和new:
static readonly string keywordIt = "it";
static readonly string keywordIif = "iif";
static readonly string keywordNew = "new";
如果您想了解更多详细信息,可以自行检查LINQ 程序集的源代码。
(顺便说一句:如果我不得不猜测的话,这里的“it”似乎是“identifier token”的缩写。)