Dynamic LINQ to DataTable: why using hardcode string "it" as DataRow

c# dynamic-linq linq

Question

Let's say I have aDataTable containing three columnsC1 , 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");

I employ the Nuget dynamic linqGroupBy columns C1 and C2 like the code below, which is flawless:

 var output = dt.AsEnumerable()
            .AsQueryable()
            .GroupBy("new(it[\"C1\"] as C1, it[\"C2\"] as C2)", "it");

If you look closely, you'll see a a fixed stringit to appear asDataRow I get this concept from:

Group by Dynamic Linq

If I attempt to alterit as a stringrow for instance:

GroupBy("new(row[\"C1\"] as C1, row[\"C2\"] as C2)", "row");

I'll encounter a runtime error:

No property or field 'row' exists in type 'DataRow'

So, I don't really get why I have to hardcode.it as DataRow ? Is there a rationale to this.

1
4
5/23/2017 12:01:28 PM

Accepted Answer

The Dynamic LINQ provider is simply written in such manner. When it attempts to parse the LINQ expressions, it identifies three hard-coded keywords:it , iff , andnew :

static readonly string keywordIt = "it";
static readonly string keywordIif = "iif";
static readonly string keywordNew = "new";

If you would want to view additional information, you may inspect the LINQ assembly yourself at source.

(If I had to guess, "it" looks to be short for "identifier token" in this sentence.)

1
3/1/2013 6:04:12 PM

Popular Answer

The current item in the enumeration has to be called "something," so "it" seemed like a logical option.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow